<?php

// +----------------------------------------------------------------------

// | Description: 客户

// +----------------------------------------------------------------------

// | Author: zl

// +----------------------------------------------------------------------



namespace app\crm\controller;

use app\admin\model\ServiceLog;

use app\admin\controller\ApiCommon;

use app\admin\model\ShopModel;

use app\admin\model\SysModel;
use app\crm\model\Customer;

use app\crm\model\ShopPerson;


use app\crm\model\BalanceLog;

use app\crm\model\Setting;

use app\crm\model\SettingCategory;

use app\crm\model\Service;

use app\crm\model\ReturnVist;

use app\crm\model\ReturnVistT;

use app\crm\model\Customer as CustomerModel;

use app\crm\model\TransferShop;

use app\crm\model\CustomerConfig as CustomerConfigModel;

use app\crm\model\CustomerGrade as CustomerGradeModel;

use think\response\Json;

use think\facade\Db;



class CustomerTj extends ApiCommon

{

    protected $customerModel;

    protected $customerConfigModel;

    protected $dd   = [10];

    protected $xm   = [9,11,12];

    protected $bh   = [];

    protected $nolyType = [46,49];



    /**

     * 用于判断权限

     * @permission 无限制

     * @allow 登录用户可访问

     * @other 其他根据系统设置

     **/

    public function initialize()
    {

        $action = [

            'permission' => ['house_list','setcustomerage','getshopcj'],

            'allow' => ['users', 'info']

        ];

        event('CheckAuth',$action);

        $request = $this->request;

        $a = strtolower($request->action());



        $where = [];

        $notInArr = array_merge($this->dd,$this->xm,$this->nolyType);

        array_push($where,['category_id','=',1]);

        array_push($where,['id','not in',$notInArr]);

        $this->bh = Db::name('setting')->where($where)->column('id');



        $this->customerModel = new CustomerModel();

        $this->customerConfigModel = new CustomerConfigModel();

        if (!in_array($a, $action['permission'])) {

            parent::initialize();

        }

    }


    //获取门诊的下拉框
    public function getOutpatientService(){
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $where = [];
        array_push($where,['shop_type','=',1]);
        array_push($where,['status','=',1]);
        if(!empty($shopIds)){
            array_push($where,['shop_id','in',$shopIds]);
        }
        $shop = DB::name('shop')->where($where)->field('shop_id,shop_name')->select()->toArray();
        return resultArray(['error' => '', 'data'=>$shop]);
    }

    public function shopDk1(): Json
    {

        $request = $this->param;
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $shop_id  = $request['type']??0;
        if(empty($shop_id)){
            $where = [];
            array_push($where,['shop_type','=',1]);
            array_push($where,['status','=',1]);
            if(!empty($shopIds)){
                array_push($where,['shop_id','in',$shopIds]);
            }
            $shop_id = ShopModel::where($where)->value('shop_id');
        }

        if(in_array($shop_id,[73782774991693,73782775085647])){
            return resultArray(['error' => '该门诊暂无数据信息']);
        }

        switch ($shop_id){
            case 73782774881835:
                //中医院
                $person = $this->zyyNurseStatistics(73782774881835,$request);
                break;
            case 73782775392774:
                //济南门诊
                $person = $this->jnNurseStatistics(73782775392774,$request);
                break;
            case 73782775206631:
                //西安
                $person = $this->xaNurseStatistics(73782775206631,$request);
                break;
            case 73782775377728:
                //石家庄
                $person = $this->xjzNurseStatistics(73782775377728,$request);
                break;
            case 73782775131388:
                //昆明
                $person = $this->kmNurseStatistics(73782775131388,$request);
                break;
            default:
                return resultArray(['error' => '暂无门诊护理统计数据']);

        }
        return resultArray(['error' => '', 'data'=>$person]);
    }


    //公共使用
    public function a($shop_id,$request){
        $map  =  [
            ['shop_id','=',$shop_id],
            ['status','=',1],
        ];
        $craft_fee = DB::name('shop_service_entry')->where($map)->field('craft_fee,project_id')->select()->toArray();
        $person = ShopPerson::where($map)->field('id,name,shop_name,station_name,market_name,shop_id')->select()->toArray();
        $project_craft_fee = DB::name('shop_project_entry')->where($map)->field('craft_fee,project_id')->select()->toArray();

        $public_where  = [];
        $start_time = isset($request['start_time'])?$request['start_time']:0;
        $end_time = isset($request['end_time'])?$request['end_time']:0;
        if(!empty($start_time)){
            array_push($public_where,['create_time','>=',strtotime($start_time)]);
        }
        if(!empty($end_time)){
            array_push($public_where,['create_time','<=',strtotime($end_time."23:59:59")]);
        }
        array_push($public_where,['shop_id','=',$shop_id]);

        return [$craft_fee,$person,$public_where,$project_craft_fee];
    }


    public function searchService($public_where,$where){
        $books = Db::name('service_log')
            ->where($public_where)
            ->where($where)
           ->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project,id')->select()->toArray();
        return $books;
    }




    //中医院门诊统计
    public function zyyNurseStatistics($shop_id,$request){
        list($craft_fee,$person,$public_where)= $this->a($shop_id,$request);
        //获取标签为内部员工的客户id
        $one = $two  = $three = $four = $five = $six = $seven = $eight = $nine = $ten = [];
        $craft_fee_arr = [];
        foreach($craft_fee as $kk=>$vv){
            if(isset($craft_fee_arr[$vv['craft_fee']])){
                $craft_fee_arr[$vv['craft_fee']][]=$vv['project_id'];
            }else{
                $craft_fee_arr[$vv['craft_fee']][]=$vv['project_id'];
            }
        }


        $title = [
            ['value'=>'one','label'=>'2元'],
            ['value'=>'two','label'=>'5元'],
            ['value'=>'three','label'=>'8元'],
            ['value'=>'four','label'=>'10元'],
            ['value'=>'five','label'=>'15元'],
            ['value'=>'six','label'=>'20元'],
            ['value'=>'seven','label'=>'25元'],
            ['value'=>'eight','label'=>'30元'],
            ['value'=>'nine','label'=>'45元'],
            ['value'=>'ten','label'=>'50元']
        ];
        $customer_ids =Customer::whereRaw("FIND_IN_SET(682,member_label)")->where('shop_id',$shop_id)
            ->column('id');

        foreach($person as $k=>&$v){
            $oneDatas = $twoDatas  = $threeDatas = $fourDatas = $fiveDatas = $sixDatas = $sevenDatas = $eightDatas = $nineDatas = $tenDatas =  [];
            $oneArr = $twoArr  = $threeArr = $fourArr = $fiveArr = $sixArr = $sevenArr = $eightArr = $nineArr = $tenArr =   [];
            $service_log_id = [];
            $customer_id = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_id_one',$v['id']);
                    $query->whereOr('nurse_id_two',$v['id']);
                })->column('customer_id');
            $v['physicianCount'] = 0;
            $physicianData =[];
            if(!empty($customer_id)){
                $customer_id = array_count_values($customer_id);
                foreach ($customer_id as $k=>$value){
                    if(in_array($k,$customer_ids)){
                        array_push($physicianData,$value);
                    }
                }
            }
            $v['physicianCount'] = array_sum($physicianData); //医师数据


            $map =[];
            array_push($map,['nurse_one','=',$v['id']]);
            array_push($map,['is_cancel','<>',2]);

            $books =$this->searchService($public_where,$map);

            $service_log_id_one = array_column($books,'id');

            foreach($books as $key=>$val){
                $nurse_one_project = explode(',',$val['nurse_one_project']);
                if(!empty($nurse_one_project)){
                    $counts = array_count_values($nurse_one_project);
                    foreach($counts as $kkk=>$vvv){
                        if(in_array($kkk,$one))  array_push($oneDatas,$vvv);
                        if(in_array($kkk,$two))  array_push($twoDatas,$vvv);
                        if(in_array($kkk,$three)) array_push($threeDatas,$vvv);
                        if(in_array($kkk,$four)) array_push($fourDatas,$vvv);
                        if(in_array($kkk,$five)) array_push($fiveDatas,$vvv);
                        if(in_array($kkk,$six))  array_push($sixDatas,$vvv);
                        if(in_array($kkk,$seven)) array_push($sevenDatas,$vvv);
                        if(in_array($kkk,$eight)) array_push($eightDatas,$vvv);
                        if(in_array($kkk,$nine)) array_push($nineDatas,$vvv);
                        if(in_array($kkk,$ten)) array_push($tenDatas,$vvv);
                    }
                }
            }

            $map =[];
            array_push($map,['nurse_two','=',$v['id']]);
            array_push($map,['is_cancel','<>',2]);
            $books =$this->searchService($public_where,$map);

            $service_log_id_two = array_column($books,'id');
            foreach($books as $key=>$val){
                $nurse_two_project = explode(',',$val['nurse_two_project']);
                if(!empty($nurse_two_project)){
                    $counts = array_count_values($nurse_two_project);
                    foreach($counts as $kkk=>$vvv){
                        if(in_array($kkk,$one))  array_push($oneDatas,$vvv);
                        if(in_array($kkk,$two))  array_push($twoDatas,$vvv);
                        if(in_array($kkk,$three)) array_push($threeDatas,$vvv);
                        if(in_array($kkk,$four)) array_push($fourDatas,$vvv);
                        if(in_array($kkk,$five)) array_push($fiveDatas,$vvv);
                        if(in_array($kkk,$six))  array_push($sixDatas,$vvv);
                        if(in_array($kkk,$seven)) array_push($sevenDatas,$vvv);
                        if(in_array($kkk,$eight)) array_push($eightDatas,$vvv);
                        if(in_array($kkk,$nine)) array_push($nineDatas,$vvv);
                        if(in_array($kkk,$ten)) array_push($tenDatas,$vvv);
                    }
                }
            }

            $service_log_id = array_unique(array_merge($service_log_id_one,$service_log_id_two));
            $control_map = [
                ['service_log_id','in',$service_log_id],
                ['nurse_id','=',$v['id']]
            ];
            $serviceLogControl = DB::name('service_log_control')->where($public_where)->where($control_map)->group('service_item')->field('service_item,count(service_item) as num')->select()->toArray();

            foreach($serviceLogControl as $kk=>$vv){
                if(in_array($vv['service_item'],$one))  array_push($oneArr,$vvv['num']);
                if(in_array($vv['service_item'],$two))  array_push($twoArr,$vvv['num']);
                if(in_array($vv['service_item'],$three)) array_push($threeArr,$vvv['num']);
                if(in_array($vv['service_item'],$four)) array_push($fourArr,$vvv['num']);
                if(in_array($vv['service_item'],$five)) array_push($fiveArr,$vvv['num']);
                if(in_array($vv['service_item'],$six))  array_push($sixArr,$vvv['num']);
                if(in_array($vv['service_item'],$seven)) array_push($sevenArr,$vvv['num']);
                if(in_array($vv['service_item'],$eight)) array_push($eightArr,$vvv['num']);
                if(in_array($vv['service_item'],$nine)) array_push($nineArr,$vvv['num']);
                if(in_array($vv['service_item'],$ten))  array_push($tenArr,$vvv['num']);
            }

            $oneArr = array_sum($oneArr);      $twoArr = array_sum($twoArr);  $threeArr = array_sum($threeArr);
            $fourArr = array_sum($fourArr);    $fiveArr = array_sum($fiveArr);  $sixArr = array_sum($sixArr);
            $sevenArr = array_sum($sevenArr);  $eightArr = array_sum($eightArr);  $nineArr = array_sum($nineArr);
            $tenArr = array_sum($tenArr);

            $oneCount = count($oneDatas);      $twoCount= count($twoDatas);   $threeCount = count($threeDatas);
            $fourCount = count($fourDatas);    $fiveCount = count($fiveDatas);   $sixCount = count($sixDatas);
            $sevenCount = count($eightDatas);    $eightCount = count($eightDatas);   $nineCount = count($nineDatas);
            $tenCount = count($tenDatas);


            $v['one'] =  bcadd($oneCount,$oneArr);
            $v['two'] =   bcadd($twoCount,$twoArr);
            $v['three'] =   bcadd($threeCount,$threeArr);
            $v['four'] =   bcadd($fourCount,$fourArr);
            $v['five'] =   bcadd($fiveCount,$fiveArr);
            $v['six'] =   bcadd($sixCount,$sixArr);
            $v['seven'] =   bcadd($sevenCount,$sevenArr);
            $v['eight'] =   bcadd($eightCount,$eightArr);
            $v['nine'] =   bcadd($nineCount,$nineArr);
            $v['ten'] =   bcadd($tenCount,$tenArr);
            $v['title'] = [
                ['value'=>$v['one'],'label'=>'one'],
                ['value'=> $v['two'],'label'=>'two'],
                ['value'=> $v['three'],'label'=>'three'],
                ['value'=>$v['four'],'label'=>'four'],
                ['value'=>$v['six'],'label'=>'five'],
                ['value'=>$v['seven'],'label'=>'six'],
                ['value'=>$v['eight'],'label'=>'seven'],
                ['value'=>$v['nine'],'label'=>'eight'],
                ['value'=>$v['ten'],'label'=>'nine'],
                ['value'=>$v['ten'],'label'=>'ten'],
            ];
            $v['count_sum'] =  $v['physicianCount']+$v['one']+$v['two']+$v['three']+ $v['four']+$v['five']+$v['six']+$v['seven']+$v['eight']+$v['nine']+ $v['ten'];
        }
        return ['list'=>[['list'=>$person,'market_name'=>$person[0]['market_name']]],'title'=>$title,'is_show_doctor'=>true,'is_show_setUpfee'=>false];
    }
    //济南门诊统计
    public function jnNurseStatistics($shop_id,$request){
        //获取标签为内部员工的客户id
        list($craft_fee,$person,$public_where)= $this->a($shop_id,$request);

        $one = $two  = $three = $four = $five = $six = $seven = $eight  = $ten =  [];

        foreach($craft_fee as $kk=>$vv){

            switch ($vv['craft_fee']){
                case 2.00:array_push($one,$vv['project_id']);     break;
                case 5.00:array_push($two,$vv['project_id']);     break;
                case 8.00:array_push($three,$vv['project_id']);   break;
                case 10.00:array_push($four,$vv['project_id']);   break;
                case 15.00:array_push($five,$vv['project_id']);   break;
                case 20.00:array_push($six,$vv['project_id']);    break;
                case 25.00:array_push($seven,$vv['project_id']);  break;
                case 30.00:array_push($eight,$vv['project_id']);  break;
                case 50.00:array_push($ten,$vv['project_id']);    break;
            }
        }
        $title = [
            ['value'=>'one','label'=>'2元'],
            ['value'=>'two','label'=>'5元'],
            ['value'=>'three','label'=>'8元'],
            ['value'=>'four','label'=>'10元'],
            ['value'=>'five','label'=>'15元'],
            ['value'=>'six','label'=>'20元'],
            ['value'=>'seven','label'=>'25元'],
            ['value'=>'eight','label'=>'30元'],
            ['value'=>'ten','label'=>'50元']
        ];

        foreach($person as $k=>&$v){
            $oneDatas = $twoDatas  = $threeDatas = $fourDatas = $fiveDatas = $sixDatas = $sevenDatas = $eightDatas  = $tenDatas =  [];

            $map =[];
            array_push($map,['nurse_one','=',$v['id']]);
            array_push($map,['is_cancel','<>',2]);
            $books =$this->searchService($public_where,$map);

            foreach($books as $key=>$val){
                $nurse_one_project = explode(',',$val['nurse_one_project']);
                if(!empty($nurse_one_project)){
                    $counts = array_count_values($nurse_one_project);
                    foreach($counts as $kkk=>$vvv){
                        if(in_array($kkk,$one))  array_push($oneDatas,$vvv);
                        if(in_array($kkk,$two))  array_push($twoDatas,$vvv);
                        if(in_array($kkk,$three)) array_push($threeDatas,$vvv);
                        if(in_array($kkk,$four)) array_push($fourDatas,$vvv);
                        if(in_array($kkk,$five)) array_push($fiveDatas,$vvv);
                        if(in_array($kkk,$six))  array_push($sixDatas,$vvv);
                        if(in_array($kkk,$seven)) array_push($sevenDatas,$vvv);
                        if(in_array($kkk,$eight)) array_push($eightDatas,$vvv);
                        if(in_array($kkk,$ten)) array_push($tenDatas,$vvv);
                    }
                }
            }
            $map =[];
            array_push($map,['nurse_two','=',$v['id']]);
            array_push($map,['is_cancel','<>',2]);
            $books =$this->searchService($public_where,$map);
            foreach($books as $key=>$val){
                $nurse_two_project = explode(',',$val['nurse_two_project']);
                if(!empty($nurse_two_project)){
                    $counts = array_count_values($nurse_two_project);
                    foreach($counts as $kkk=>$vvv){
                        if(in_array($kkk,$one))  array_push($oneDatas,$vvv);
                        if(in_array($kkk,$two))  array_push($twoDatas,$vvv);
                        if(in_array($kkk,$three)) array_push($threeDatas,$vvv);
                        if(in_array($kkk,$four)) array_push($fourDatas,$vvv);
                        if(in_array($kkk,$five)) array_push($fiveDatas,$vvv);
                        if(in_array($kkk,$six))  array_push($sixDatas,$vvv);
                        if(in_array($kkk,$seven)) array_push($sevenDatas,$vvv);
                        if(in_array($kkk,$eight)) array_push($eightDatas,$vvv);
                        if(in_array($kkk,$ten)) array_push($tenDatas,$vvv);
                    }
                }
            }

            $v['one'] =  count($oneDatas);
            $v['two'] =  count($twoDatas);
            $v['three'] =  count($threeDatas);
            $v['four'] =  count($fourDatas);
            $v['five'] =  count($fiveDatas);
            $v['six'] =  count($sixDatas);
            $v['seven'] =  count($sevenDatas);
            $v['eight'] =  count($eightDatas);
            $v['ten'] =  count($tenDatas);

            $v['title'] = [
                ['value'=>count($oneDatas),'label'=>'one'],
                ['value'=>count($twoDatas),'label'=>'two'],
                ['value'=>count($threeDatas),'label'=>'three'],
                ['value'=>count($fourDatas),'label'=>'four'],
                ['value'=>count($fiveDatas),'label'=>'five'],
                ['value'=>count($sixDatas),'label'=>'six'],
                ['value'=>count($sevenDatas),'label'=>'seven'],
                ['value'=>count($eightDatas),'label'=>'eight'],
                ['value'=>count($tenDatas),'label'=>'ten'],
            ];

            $v['count_sum'] =  $v['one']+$v['two']+$v['three']+ $v['four']+$v['five']+$v['six']+$v['eight']+ $v['ten'];
        }
        return ['list'=>[['list'=>$person,'market_name'=>$person[0]['market_name']]],'title'=>$title];
    }
    //西安门诊统计
    public function xaNurseStatistics($shop_id,$request){
        //获取标签为内部员工的客户id
        list($craft_fee,$person,$public_where)= $this->a($shop_id,$request);

        $one = $two  = $three = $four = $five = $six = $seven = $eight  = $ten =  [];

        foreach($craft_fee as $kk=>$vv){
            switch ($vv['craft_fee']){
                case 2.00:array_push($one,$vv['project_id']);     break;
                case 5.00:array_push($two,$vv['project_id']);     break;
                case 8.00:array_push($three,$vv['project_id']);   break;
                case 10.00:array_push($four,$vv['project_id']);   break;
                case 15.00:array_push($five,$vv['project_id']);   break;
                case 20.00:array_push($six,$vv['project_id']);    break;
                case 25.00:array_push($seven,$vv['project_id']);  break;
                case 30.00:array_push($eight,$vv['project_id']);  break;
                case 50.00:array_push($ten,$vv['project_id']);    break;
            }
        }

        $title = [
            ['value'=>'one','label'=>'2元'],
            ['value'=>'two','label'=>'5元'],
            ['value'=>'three','label'=>'8元'],
            ['value'=>'four','label'=>'10元'],
            ['value'=>'five','label'=>'15元'],
            ['value'=>'six','label'=>'20元'],
            ['value'=>'seven','label'=>'25元'],
            ['value'=>'eight','label'=>'30元'],
            ['value'=>'ten','label'=>'50元']
        ];

        foreach($person as $k=>&$v){
            $oneDatas = $twoDatas  = $threeDatas = $fourDatas = $fiveDatas = $sixDatas = $sevenDatas = $eightDatas  = $tenDatas =  [];

            $map =[];
            array_push($map,['nurse_one','=',$v['id']]);
            array_push($map,['is_cancel','<>',2]);
            $books =$this->searchService($public_where,$map);

            foreach($books as $key=>$val){
                $nurse_one_project = explode(',',$val['nurse_one_project']);
                if(!empty($nurse_one_project)){
                    $counts = array_count_values($nurse_one_project);
                    foreach($counts as $kkk=>$vvv){
                        if(in_array($kkk,$one))  array_push($oneDatas,$vvv);
                        if(in_array($kkk,$two))  array_push($twoDatas,$vvv);
                        if(in_array($kkk,$three)) array_push($threeDatas,$vvv);
                        if(in_array($kkk,$four)) array_push($fourDatas,$vvv);
                        if(in_array($kkk,$five)) array_push($fiveDatas,$vvv);
                        if(in_array($kkk,$six))  array_push($sixDatas,$vvv);
                        if(in_array($kkk,$seven)) array_push($sevenDatas,$vvv);
                        if(in_array($kkk,$eight)) array_push($eightDatas,$vvv);
                        if(in_array($kkk,$ten)) array_push($tenDatas,$vvv);
                    }
                }
            }

            $map =[];
            array_push($map,['nurse_two','=',$v['id']]);
            array_push($map,['is_cancel','<>',2]);
            $books =$this->searchService($public_where,$map);
            foreach($books as $key=>$val){
                $nurse_two_project = explode(',',$val['nurse_two_project']);
                if(!empty($nurse_two_project)){
                    $counts = array_count_values($nurse_two_project);
                    foreach($counts as $kkk=>$vvv){
                        if(in_array($kkk,$one))  array_push($oneDatas,$vvv);
                        if(in_array($kkk,$two))  array_push($twoDatas,$vvv);
                        if(in_array($kkk,$three)) array_push($threeDatas,$vvv);
                        if(in_array($kkk,$four)) array_push($fourDatas,$vvv);
                        if(in_array($kkk,$five)) array_push($fiveDatas,$vvv);
                        if(in_array($kkk,$six))  array_push($sixDatas,$vvv);
                        if(in_array($kkk,$seven)) array_push($sevenDatas,$vvv);
                        if(in_array($kkk,$eight)) array_push($eightDatas,$vvv);
                        if(in_array($kkk,$ten)) array_push($tenDatas,$vvv);
                    }
                }
            }


            $v['one'] =  count($oneDatas);
            $v['two'] =  count($twoDatas);
            $v['three'] =  count($threeDatas);
            $v['four'] =  count($fourDatas);
            $v['five'] =  count($fiveDatas);
            $v['six'] =  count($sixDatas);
            $v['seven'] =  count($sevenDatas);
            $v['eight'] =  count($eightDatas);
            $v['ten'] =  count($tenDatas);

            $v['title'] = [
                ['value'=>count($oneDatas),'label'=>'one'],
                ['value'=>count($twoDatas),'label'=>'two'],
                ['value'=>count($threeDatas),'label'=>'three'],
                ['value'=>count($fourDatas),'label'=>'four'],
                ['value'=>count($fiveDatas),'label'=>'five'],
                ['value'=>count($sixDatas),'label'=>'six'],
                ['value'=>count($sevenDatas),'label'=>'seven'],
                ['value'=>count($eightDatas),'label'=>'eight'],
                ['value'=>count($tenDatas),'label'=>'ten'],
            ];


            $v['count_sum'] =  $v['one']+$v['two']+$v['three']+ $v['four']+$v['five']+$v['six']+$v['eight']+ $v['ten'];
        }
        return ['list'=>[['list'=>$person,'market_name'=>$person[0]['market_name']]],'title'=>$title];
    }
    //石家庄门诊统计
    public function xjzNurseStatistics($shop_id,$request){
        //石家庄门诊
        list($craft_fee,$person,$public_where)= $this->a($shop_id,$request);
        $five = $eight = [];
        foreach($craft_fee as $kk=>$vv){
            switch ($vv['craft_fee']){
                case 15.00:array_push($five,$vv['project_id']);   break;
                case 30.00:array_push($eight,$vv['project_id']);  break;
            }
        }
        $title = [
            ['value'=>'five','label'=>'15元'],
            ['value'=>'eight','label'=>'30元'],
        ];
        $setUpFee = [
            ['value'=>'set_up_one','label'=>'6元'],
        ];

        foreach($person as $k=>&$v){
            $fiveDatas  = $eightDatas  =  [];
            $peitaifei = [];

            $books = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_one',$v['id']);
                    $query->where('nurse_two','<>',$v['id']);
                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project')->select()->toArray();
            $map =[];
            array_push($map,['nurse_two','=',$v['id']]);
            array_push($map,['is_cancel','<>',2]);
            $books =$this->searchService($public_where,$map);
            foreach($books as $key=>$val){
                $nurse_one_project = explode(',',$val['nurse_one_project']);
                $peitaifei = array_merge($nurse_one_project,$peitaifei);
            }
            $books = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_one','<>',$v['id']);
                    $query->where('nurse_two',$v['id']);
                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project')->select()->toArray();
            foreach($books as $key=>$val){
                $nurse_two_project = explode(',',$val['nurse_two_project']);
                $peitaifei = array_merge($nurse_two_project,$peitaifei);
            }
            $books = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_one',$v['id']);
                    $query->where('nurse_two',$v['id']);
                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project')->select()->toArray();
            foreach($books as $key=>$val){
                $nurse_one_project = explode(',',$val['nurse_one_project']);
                $nurse_two_project = explode(',',$val['nurse_two_project']);
                $nurse_project = array_unique(array_merge($nurse_one_project,$nurse_two_project));
                $peitaifei = array_merge($nurse_project,$peitaifei);
            }

            $v['set_up_one'] = count($peitaifei);
            $v['setUpFee'] = [
                ['value'=>count($peitaifei),'label'=>'set_up_one'],
            ];
            $books = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_id_one',$v['id']);
                    $query->whereOr('nurse_id_two',$v['id']);
                })->column('goods_id');

            if(!empty($books)){
                $counts = array_count_values($books);
                foreach($counts as $kkk=>$vvv){
                    if(in_array($kkk,$five)) array_push($fiveDatas,$vvv);
                    if(in_array($kkk,$eight)) array_push($eightDatas,$vvv);
                }
            }
            $v['five'] =  count($fiveDatas);
            $v['eight'] =  count($eightDatas);
            $v['title'] = [
                ['value'=>count($fiveDatas),'label'=>'five'],
                ['value'=>count($eightDatas),'label'=>'eight'],
            ];
            $v['count_sum'] =  $v['five']+$v['eight']+$v['set_up_one'];
        }
        return ['list'=>[['list'=>$person,'market_name'=>$person[0]['market_name']]],'title'=>$title,'set_up_fee'=>$setUpFee,'is_show_setUpfee'=>true];
    }
    //昆明门诊
    public function kmNurseStatistics($shop_id,$request){
        //昆明门诊
        list($craft_fee,$person,$public_where,$project_craft_fee)= $this->a($shop_id,$request);
        $project_one = $project_two  = $project_three = $project_four = $project_five = $project_six = $project_seven = $project_eight  = $project_ten =  []; //项目手工费(配台费)
        foreach($project_craft_fee as $kk=>$vv){
            switch ($vv['craft_fee']){
                case 2.00:array_push($project_one,$vv['project_id']);     break;
                case 5.00:array_push($project_two,$vv['project_id']);     break;
                case 8.00:array_push($project_three,$vv['project_id']);   break;
                case 10.00:array_push($project_four,$vv['project_id']);   break;
                case 15.00:array_push($project_five,$vv['project_id']);   break;
                case 17.00:array_push($project_six,$vv['project_id']);    break;
                case 22.00:array_push($project_seven,$vv['project_id']);  break;
                case 27.00:array_push($project_eight,$vv['project_id']);  break;
                case 100.00:array_push($project_ten,$vv['project_id']);   break;
            }
        }
        $setUpFee = [
            ['value'=>'set_up_one','label'=>'2元'],
            ['value'=>'set_up_two','label'=>'5元'],
            ['value'=>'set_up_three','label'=>'8元'],
            ['value'=>'set_up_four','label'=>'10元'],
            ['value'=>'set_up_five','label'=>'15元'],
            ['value'=>'set_up_six','label'=>'17元'],
            ['value'=>'set_up_seven','label'=>'22元'],
            ['value'=>'set_up_eight','label'=>'27元'],
            ['value'=>'set_up_ten','label'=>'100元'],
        ];
        $one = $two  = $three = $four = $five = $six = $seven = $eight  = $nine = $ten =  []; //跟台护士数据

        foreach($craft_fee as $kk=>$vv){
            switch ($vv['craft_fee']){
                case 2.00:array_push($one,$vv['project_id']);     break;
                case 5.00:array_push($two,$vv['project_id']);     break;
                case 8.00:array_push($three,$vv['project_id']);   break;
                case 10.00:array_push($four,$vv['project_id']);   break;
                case 15.00:array_push($five,$vv['project_id']);   break;
                case 17.00:array_push($six,$vv['project_id']);    break;
                case 22.00:array_push($seven,$vv['project_id']);  break;
                case 27.00:array_push($eight,$vv['project_id']);  break;
                case 47.00:array_push($nine,$vv['project_id']);  break;
                case 100.00:array_push($ten,$vv['project_id']);   break;
            }
        }
        $title = [
            ['value'=>'one','label'=>'2元'],
            ['value'=>'two','label'=>'5元'],
            ['value'=>'three','label'=>'8元'],
            ['value'=>'four','label'=>'10元'],
            ['value'=>'five','label'=>'15元'],
            ['value'=>'six','label'=>'17元'],
            ['value'=>'seven','label'=>'22元'],
            ['value'=>'eight','label'=>'27元'],
            ['value'=>'nine','label'=>'47元'],
            ['value'=>'ten','label'=>'100元']
        ];

        foreach($person as $k=>&$v){
            $project_one_data = $project_two_data  = $project_three_data = $project_four_data = $project_five_data = $project_six_data = $project_seven_data = $project_eight_data  = $project_ten_data =  []; //项目手工费(配台费)
            $peitaifei = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_id_one',$v['id']);
                    $query->whereOr('nurse_id_two',$v['id']);
                })->column('goods_id');
            if(!empty($peitaifei)){
                $ptf_counts = array_count_values($peitaifei);
                foreach($ptf_counts as $kkk=>$vvv){
                    if(in_array($kkk,$project_one)) array_push($project_one_data,$vvv);
                    if(in_array($kkk,$project_two)) array_push($project_two_data,$vvv);
                    if(in_array($kkk,$project_three)) array_push($project_three_data,$vvv);
                    if(in_array($kkk,$project_four)) array_push($project_four_data,$vvv);
                    if(in_array($kkk,$project_five)) array_push($project_five_data,$vvv);
                    if(in_array($kkk,$project_six)) array_push($project_six_data,$vvv);
                    if(in_array($kkk,$project_seven)) array_push($project_seven_data,$vvv);
                    if(in_array($kkk,$project_eight)) array_push($project_eight_data,$vvv);
                    if(in_array($kkk,$project_ten)) array_push($project_ten_data,$vvv);
                }
            }

            $v['project_one'] = array_sum($project_one_data);
            $v['project_two'] = array_sum($project_two_data);
            $v['project_three'] = array_sum($project_three_data);
            $v['project_four'] = array_sum($project_four_data);
            $v['project_five'] = array_sum($project_five_data);
            $v['project_six'] = array_sum($project_six_data);
            $v['project_seven'] = array_sum($project_seven_data);
            $v['project_eight'] = array_sum($project_eight_data);
            $v['project_ten'] = array_sum($project_ten_data);
            $v['setUpFee'] = [
                ['value'=>$v['project_one'],'label'=>'project_one'],
                ['value'=>$v['project_two'],'label'=>'project_two'],
                ['value'=>$v['project_three'],'label'=>'project_three'],
                ['value'=>$v['project_four'],'label'=>'project_four'],
                ['value'=> $v['project_five'],'label'=>'project_five'],
                ['value'=>$v['project_six'],'label'=>'project_six'],
                ['value'=>$v['project_seven'],'label'=>'project_seven'],
                ['value'=>$v['project_eight'],'label'=>'project_eight'],
                ['value'=>$v['project_ten'],'label'=>'project_ten'],
            ];

            //手工费
            $craft_fee = []; //手工费
            $oneDatas = $twoDatas  = $threeDatas = $fourDatas = $fiveDatas = $sixDatas = $sevenDatas = $eightDatas =$nineDatas = $tenDatas =  [];
            $books = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_one',$v['id']);
                    $query->where('nurse_two','<>',$v['id']);
                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project')->select()->toArray();
            foreach($books as $key=>$val){
                $nurse_one_project = explode(',',$val['nurse_one_project']);
                $craft_fee = array_merge($nurse_one_project,$craft_fee);
            }
            $books = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_one','<>',$v['id']);
                    $query->where('nurse_two',$v['id']);
                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project')->select()->toArray();
            foreach($books as $key=>$val){
                $nurse_two_project = explode(',',$val['nurse_two_project']);
                $craft_fee = array_merge($nurse_two_project,$craft_fee);
            }
            $books = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($public_where)
                ->where(function($query)use($v){
                    $query->where('nurse_one',$v['id']);
                    $query->where('nurse_two',$v['id']);
                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project')->select()->toArray();
            foreach($books as $key=>$val){
                $nurse_one_project = explode(',',$val['nurse_one_project']);
                $nurse_two_project = explode(',',$val['nurse_two_project']);
                $nurse_project = array_unique(array_merge($nurse_one_project,$nurse_two_project));
                $craft_fee = array_merge($nurse_project,$craft_fee);
            }
            if(!empty($craft_fee)){
                $sg_counts = array_count_values($craft_fee);
                foreach($sg_counts as $kkk=>$vvv){
                    if(in_array($kkk,$one)) array_push($oneDatas,$vvv);
                    if(in_array($kkk,$two)) array_push($twoDatas,$vvv);
                    if(in_array($kkk,$three)) array_push($threeDatas,$vvv);
                    if(in_array($kkk,$four)) array_push($fourDatas,$vvv);
                    if(in_array($kkk,$five)) array_push($fiveDatas,$vvv);
                    if(in_array($kkk,$six)) array_push($sixDatas,$vvv);
                    if(in_array($kkk,$seven)) array_push($sevenDatas,$vvv);
                    if(in_array($kkk,$eight)) array_push($eightDatas,$vvv);
                    if(in_array($kkk,$nine)) array_push($nineDatas,$vvv);
                    if(in_array($kkk,$ten)) array_push($tenDatas,$vvv);
                }
            }

            $v['one'] = array_sum($oneDatas);
            $v['two'] = array_sum($twoDatas);
            $v['three'] = array_sum($threeDatas);
            $v['four'] = array_sum($fourDatas);
            $v['five'] = array_sum($fiveDatas);
            $v['six'] = array_sum($sixDatas);
            $v['seven'] = array_sum($sevenDatas);
            $v['eight'] = array_sum($eightDatas);
            $v['nine'] = array_sum($nineDatas);
            $v['ten'] = array_sum($tenDatas);

            $v['title'] = [
                ['value'=>$v['one'],'label'=>'one'],
                ['value'=>$v['two'],'label'=>'two'],
                ['value'=>$v['three'],'label'=>'three'],
                ['value'=> $v['four'],'label'=>'four'],
                ['value'=> $v['five'],'label'=>'five'],
                ['value'=>$v['six'],'label'=>'six'],
                ['value'=>$v['seven'],'label'=>'seven'],
                ['value'=>$v['eight'],'label'=>'eight'],
                ['value'=>$v['nine'],'label'=>'nine'],
                ['value'=>$v['ten'],'label'=>'ten'],
            ];
            $project_sum = $v['project_one']+$v['project_two']+$v['project_three']+ $v['project_four']+$v['project_five']+$v['project_six']+$v['project_seven']+$v['project_eight']+ $v['project_ten'];
            $sj_sum = $v['one']+$v['two']+$v['three']+ $v['four']+$v['five']+$v['six']+$v['seven']+$v['eight']+$v['nine']+ $v['ten'];
            $v['count_sum'] =  $project_sum + $sj_sum;

        }
        return ['list'=>[['list'=>$person,'market_name'=>$person[0]['market_name']]],'title'=>$title,'set_up_fee'=>$setUpFee,'is_show_setUpfee'=>true,'is_show_doctor'=>false];

    }

    //获取手工费和配台费
    public function getSetupCraft($shop_id){
        $set_up_fee = $craft_fee = [];
        //set_up_fee 配台费
        //craft_fee 手工费
        switch ($shop_id){
            case 73782774881835:
                //中医院
                $craft_fee = [
                    ['value'=>'one','label'=>'2元'],
                    ['value'=>'two','label'=>'5元'],
                    ['value'=>'three','label'=>'8元'],
                    ['value'=>'four','label'=>'10元'],
                    ['value'=>'five','label'=>'15元'],
                    ['value'=>'six','label'=>'20元'],
                    ['value'=>'seven','label'=>'25元'],
                    ['value'=>'eight','label'=>'30元'],
                    ['value'=>'nine','label'=>'45元'],
                    ['value'=>'ten','label'=>'50元']
                ];
                break;
            case 73782775392774:
                //济南门诊
                $craft_fee = [
                    ['value'=>'one','label'=>'2元'],
                    ['value'=>'two','label'=>'5元'],
                    ['value'=>'three','label'=>'8元'],
                    ['value'=>'four','label'=>'10元'],
                    ['value'=>'five','label'=>'15元'],
                    ['value'=>'six','label'=>'20元'],
                    ['value'=>'seven','label'=>'25元'],
                    ['value'=>'eight','label'=>'30元'],
                    ['value'=>'ten','label'=>'50元']
                ];
                break;
            case 73782775206631:
                //西安
                $craft_fee = [
                    ['value'=>'one','label'=>'2元'],
                    ['value'=>'two','label'=>'5元'],
                    ['value'=>'three','label'=>'8元'],
                    ['value'=>'four','label'=>'10元'],
                    ['value'=>'five','label'=>'15元'],
                    ['value'=>'six','label'=>'20元'],
                    ['value'=>'seven','label'=>'25元'],
                    ['value'=>'eight','label'=>'30元'],
                    ['value'=>'ten','label'=>'50元']
                ];
                break;
            case 73782775377728:
                //石家庄
                $craft_fee = [
                    ['value'=>'five','label'=>'15元'],
                    ['value'=>'eight','label'=>'30元'],
                ];
                $set_up_fee = [
                    ['value'=>'set_up_one','label'=>'6元'],
                ];
                break;
            case 73782775131388:
                //昆明
                $craft_fee = [
                    ['value'=>'one','label'=>'2元'],
                    ['value'=>'two','label'=>'5元'],
                    ['value'=>'three','label'=>'8元'],
                    ['value'=>'four','label'=>'10元'],
                    ['value'=>'five','label'=>'15元'],
                    ['value'=>'six','label'=>'17元'],
                    ['value'=>'seven','label'=>'22元'],
                    ['value'=>'eight','label'=>'27元'],
                    ['value'=>'nine','label'=>'47元'],
                    ['value'=>'ten','label'=>'100元']
                ];
                $set_up_fee = [
                    ['value'=>'project_one','label'=>'2元'],
                    ['value'=>'project_two','label'=>'5元'],
                    ['value'=>'project_three','label'=>'8元'],
                    ['value'=>'project_four','label'=>'10元'],
                    ['value'=>'project_five','label'=>'15元'],
                    ['value'=>'project_six','label'=>'17元'],
                    ['value'=>'project_seven','label'=>'22元'],
                    ['value'=>'project_eight','label'=>'27元'],
                    ['value'=>'project_ten','label'=>'100元'],
                ];
                break;
        }
        return ['set_up'=>$set_up_fee,'craft_fee'=>$craft_fee];
    }

    //查看详情
    public function OutpatientCareDetail(){

        $request = $this->param;
        $type = $request['type'];
        $person_id = $request['person_id'];
        $shop_id = ShopPerson::where('id',$person_id)->value('shop_id');
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        $serviceLog = [];
        $dataCount = 0;

        $where  = [];
        $start_time = isset($request['start_time'])?$request['start_time']:0;
        $end_time = isset($request['end_time'])?$request['end_time']:0;
        if(!empty($start_time)){
            array_push($where,['create_time','>=',strtotime($start_time)]);
        }
        if(!empty($end_time)){
            array_push($where,['create_time','<=',strtotime($end_time."23:59:59")]);
        }

        //医生数据
        if($type == 'physicianCount'){
            $customer_ids =Customer::whereRaw("FIND_IN_SET(682,member_label)")->where('shop_id',$shop_id)->column('id');

            $customer_id = Db::name('service_log')
                ->where('is_cancel','<>',2)
                ->where($where)
                ->where(function($query)use($person_id){
                    $query->where('nurse_id_one',$person_id);
                    $query->whereOr('nurse_id_two',$person_id);
                })->column('customer_id');

            $physicianData = array_intersect($customer_ids,$customer_id);
            if(!empty($physicianData)){
                $serviceLog= ServiceLog::with([
                    'nurseIdOne'=>function($query){
                        $query->field('name,id');
                    },'nurseIdTwo'=>function($query){
                        $query->field('name,id');
                    },'nurseOne'=>function($query){
                        $query->field('name,id');
                    },'nurseTwo'=>function($query){
                        $query->field('name,id');
                    },'customer'=>function($query){
                        $query->with(['nurse'=>function($query){
                            $query->field('id,name');
                        }]);
                        $query->field('id,customer_name,nurse_id');
                    },'shop'=>function($query){
                        $query->field('shop_name,shop_id');
                    },'goods'=>function($query){
                        $query->field('name,id');
                    }
                ])
                    ->whereIn('customer_id',$physicianData)
                    ->where('is_cancel','<>',2)
                    ->where($where)
                    ->where(function($query)use($person_id){
                        $query->where('nurse_id_one',$person_id);
                        $query->whereOr('nurse_id_two',$person_id);
                    })->field('id,shop_id,goods_id,nurse_id_one,nurse_id_two,create_time,nurse_one,nurse_two,nurse_one_project,nurse_two_project,customer_id,service_id')
                    ->select()->toArray();
                //   var_dump($serviceLog);die;
                // foreach($serviceLog as $kk=>&$vv){
                //     $vv['customer_name'] = $vv['customer_nurse'] = '';
                //     if(!empty($vv['customer'])){
                //         $vv['customer_name'] = $vv['customer']['customer_name'];
                //         if(!empty($vv['customer']['nurse'])){
                //             $vv['customer_nurse'] = $vv['customer']['nurse']['name'];
                //         }
                //     }
                //     $vv['nurse_id_one'] = !empty($vv['nurseIdOne'])?$vv['nurseIdOne']['name']:'';
                //     $vv['nurse_id_two'] = !empty($vv['nurseIdTwo'])?$vv['nurseIdTwo']['name']:'';
                //     $vv['nurse_one'] = !empty($vv['nurseOne'])?$vv['nurseOne']['name']:'';
                //     $vv['nurse_two'] = !empty($vv['nurseTwo'])?$vv['nurseTwo']['name']:'';
                //     $vv['shop_name'] = !empty($vv['shop'])?$vv['shop']['shopName']:'';
                //     $vv['shop_id']   = !empty($vv['shop'])?$vv['shop']['shopId']:0;
                //     $vv['goods_name']   = !empty($vv['goods'])?$vv['goods']['name']:0;
                //     $vv['service_num'] = 1;
                //     if(!empty($vv['nurse_one_project'])){
                //         $nurse_one_project = explode(',',$vv['nurse_one_project']);
                //         $nurse_one_project =  DB::name('shop_person_controls')->whereIn('id',$nurse_one_project)->column('name');
                //         $vv['nurse_one_project'] = implode(',',$nurse_one_project);
                //     }
                //     if(!empty($vv['nurse_two_project'])){
                //         $nurse_two_project = explode(',',$vv['nurse_two_project']);
                //         $nurse_two_project =  DB::name('shop_person_controls')->whereIn('id',$nurse_two_project)->column('name');
                //         $vv['nurse_one_project'] = implode(',',$nurse_two_project);
                //     }
                //     unset($vv['shop'],$vv['nurseOne'],$vv['nurseTwo'],$vv['nurseIdOne'],$vv['nurseIdTwo'],$vv['customer'],$vv['goods']);
                // }

            }
        }else {
            $serviceLogIds = [];
            $setUpCraft = $this->getSetupCraft($shop_id);
            $setup = $setUpCraft['set_up'];
            $setup = array_column($setup, null, 'value');
            $setup_price = isset($setup[$type]) ? $setup[$type]['label'] : 0;
            if ($setup_price != 0) {
                //配台费
                $price = explode('元', $setup_price);
                switch ($shop_id){
                    case 73782775377728:
                        //石家庄门诊
                        $serviceLog = ServiceLog::with([
                            'nurseIdOne'=>function($query){
                                $query->field('name,id');
                            },'nurseIdTwo'=>function($query){
                                $query->field('name,id');
                            },'nurseOne'=>function($query){
                                $query->field('name,id');
                            },'nurseTwo'=>function($query){
                                $query->field('name,id');
                            },'customer'=>function($query){
                                $query->with(['nurse'=>function($query){
                                    $query->field('id,name');
                                }]);
                                $query->field('id,customer_name,nurse_id');
                            },'shop'=>function($query){
                                $query->field('shop_name,shop_id');
                            },'goods'=>function($query){
                                $query->field('name,id');
                            },'service'=>function($query){
                                $query->field('order_id,id');
                            }
                        ])
                            ->where($where)
                            ->where('is_cancel','<>',2)
                            ->where(function($query)use($person_id){
                                $query->where('nurse_one',$person_id);
                                $query->whereOr('nurse_two',$person_id);
                            })
                            ->field('id,shop_id,goods_id,nurse_id_one,nurse_id_two,create_time,nurse_one,nurse_two,nurse_one_project,nurse_two_project,customer_id');
                        $dataCount = $serviceLog->count();
                        $serviceLog= $serviceLog->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])->select()->toArray();
                        break;
                    case 73782775131388:
                        //昆明门诊
                        $map = [
                            ['shop_id','=',$shop_id],
                            ['craft_fee','=',$price[0]],
                            ['status','=',1]
                        ];
                        $project_id = DB::name('shop_project_entry')->where($map)->column('project_id');
                        if(!empty($project_id)){
                            $serviceLog = ServiceLog::with([
                                'nurseIdOne'=>function($query){
                                    $query->field('name,id');
                                },'nurseIdTwo'=>function($query){
                                    $query->field('name,id');
                                },'nurseOne'=>function($query){
                                    $query->field('name,id');
                                },'nurseTwo'=>function($query){
                                    $query->field('name,id');
                                },'customer'=>function($query){
                                    $query->with(['nurse'=>function($query){
                                        $query->field('id,name');
                                    }]);
                                    $query->field('id,customer_name,nurse_id');
                                },'shop'=>function($query){
                                    $query->field('shop_name,shop_id');
                                },'goods'=>function($query){
                                    $query->field('name,id');
                                },'service'=>function($query){
                                    $query->field('order_id,id');
                                }
                            ])
                                ->where('is_cancel','<>',2)
                                ->where($where)
                                ->where(function($query)use($person_id){
                                    $query->where('nurse_id_one',$person_id);
                                    $query->whereOr('nurse_id_two',$person_id);
                                })
                                ->whereIn('goods_id',$project_id)
                                ->field('id,shop_id,goods_id,nurse_id_one,nurse_id_two,create_time,nurse_one,nurse_two,nurse_one_project,nurse_two_project,customer_id,service_id');
                            $dataCount = $serviceLog->count();
                            $serviceLog= $serviceLog->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])->select()->toArray();
                        }
                        break;
                }
            }else{
                $craft_fee = $setUpCraft['craft_fee'];
                $craft_fee = array_column($craft_fee, null, 'value');
                $craft_fee = isset($craft_fee[$type]) ? $craft_fee[$type]['label'] : 0;
                if($craft_fee !=0){
                    $price =explode('元', $craft_fee);
                    switch ($shop_id){
                        case 73782775377728:
                            //石家庄门诊
                            $map = [
                                ['shop_id','=',$shop_id],
                                ['status','=',1],
                                ['craft_fee','=',$price[0]]
                            ];
                            $project_id = DB::name('shop_project_entry')->where($map)->column('project_id');
                            $serviceLog = ServiceLog::with([
                                'nurseIdOne'=>function($query){
                                    $query->field('name,id');
                                },'nurseIdTwo'=>function($query){
                                    $query->field('name,id');
                                },'nurseOne'=>function($query){
                                    $query->field('name,id');
                                },'nurseTwo'=>function($query){
                                    $query->field('name,id');
                                },'customer'=>function($query){
                                    $query->with(['nurse'=>function($query){
                                        $query->field('id,name');
                                    }]);
                                    $query->field('id,customer_name,nurse_id');
                                },'shop'=>function($query){
                                    $query->field('shop_name,shop_id');
                                },'goods'=>function($query){
                                    $query->field('name,id');
                                },'service'=>function($query){
                                    $query->field('order_id,id');
                                }
                            ])
                                ->where('is_cancel','<>',2)
                                ->where($where)
                                ->where(function($query)use($person_id){
                                    $query->where('nurse_id_one',$person_id);
                                    $query->whereOr('nurse_id_two',$person_id);
                                })->whereIn('goods_id',$project_id)
                                ->field('id,shop_id,goods_id,nurse_id_one,nurse_id_two,create_time,nurse_one,nurse_two,nurse_one_project,nurse_two_project,customer_id,service_id')
                                ->select()->toArray();
                            break;
                        default:
                            //手工费
                            $map = [
                                ['shop_id','=',$shop_id],
                                ['status','=',1],
                                ['craft_fee','=',$price[0]]
                            ];
                            $project_id = DB::name('shop_service_entry')->where($map)->column('project_id');

                            $books = Db::name('service_log')
                                ->where('is_cancel','<>',2)
                                ->where(function($query)use($person_id){
                                    $query->where('nurse_one',$person_id);
                                    $query->where('nurse_two','<>',$person_id);
                                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project,id')->select()->toArray();
                            foreach($books as $key=>$val){
                                $nurse_one_project = explode(',',$val['nurse_one_project']);
                                $jx_project_id = array_intersect($project_id, $nurse_one_project);
                                if(!empty($jx_project_id)){
                                    array_push($serviceLogIds,$val['id']);
                                }
                            }
                            $books = Db::name('service_log')
                                ->where('is_cancel','<>',2)
                                ->where(function($query)use($person_id){
                                    $query->where('nurse_one','<>',$person_id);
                                    $query->where('nurse_two',$person_id);
                                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project,id')->select()->toArray();
                            foreach($books as $key=>$val){
                                $nurse_two_project = explode(',',$val['nurse_two_project']);
                                $jx_project_id = array_intersect($project_id, $nurse_two_project);
                                if(!empty($jx_project_id)){
                                    array_push($serviceLogIds,$val['id']);
                                }
                            }
                            $books = Db::name('service_log')
                                ->where('is_cancel','<>',2)
                                ->where(function($query)use($person_id){
                                    $query->where('nurse_one',$person_id);
                                    $query->where('nurse_two',$person_id);
                                })->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project,id')->select()->toArray();
                            foreach($books as $key=>$val){
                                $nurse_one_project = explode(',',$val['nurse_one_project']);
                                $nurse_two_project = explode(',',$val['nurse_two_project']);
                                $nurse_project = array_merge($nurse_one_project,$nurse_two_project);
                                $jx_project_id = array_intersect($project_id, $nurse_project);
                                if(!empty($jx_project_id)){
                                    array_push($serviceLogIds,$val['id']);
                                }
                            }
                            if(!empty($serviceLogIds)){
                                $serviceLog = ServiceLog::with([
                                    'nurseIdOne'=>function($query){
                                        $query->field('name,id');
                                    },'nurseIdTwo'=>function($query){
                                        $query->field('name,id');
                                    },'nurseOne'=>function($query){
                                        $query->field('name,id');
                                    },'nurseTwo'=>function($query){
                                        $query->field('name,id');
                                    },'customer'=>function($query){
                                        $query->with(['nurse'=>function($query){
                                            $query->field('id,name');
                                        }]);
                                        $query->field('id,customer_name,nurse_id');
                                    },'shop'=>function($query){
                                        $query->field('shop_name,shop_id');
                                    },'goods'=>function($query){
                                        $query->field('name,id');
                                    },'service'=>function($query){
                                        $query->field('order_id,id');
                                    }
                                ])
                                    ->where($where)
                                    ->whereIn('id',$serviceLogIds)
                                    ->field('id,shop_id,goods_id,nurse_id_one,nurse_id_two,create_time,nurse_one,nurse_two,nurse_one_project,nurse_two_project,customer_id,service_id');
                                $dataCount = $serviceLog->count();
                                $serviceLog= $serviceLog->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])->select()->toArray();

                            }
                    }
                }
            }

        }
        if(!empty($serviceLog)){
            foreach($serviceLog as $kk=>&$vv){
                $vv['customer_name'] = $vv['customer_nurse'] = '';
                if(!empty($vv['customer'])){
                    $vv['customer_name'] = $vv['customer']['customer_name'];
                    if(!empty($vv['customer']['nurse'])){
                        $vv['customer_nurse'] = $vv['customer']['nurse']['name'];
                    }
                }
                $vv['nurse_id_one'] = !empty($vv['nurseIdOne'])?$vv['nurseIdOne']['name']:'';
                $vv['nurse_id_two'] = !empty($vv['nurseIdTwo'])?$vv['nurseIdTwo']['name']:'';
                $vv['nurse_one'] = !empty($vv['nurseOne'])?$vv['nurseOne']['name']:'';
                $vv['nurse_two'] = !empty($vv['nurseTwo'])?$vv['nurseTwo']['name']:'';
                $vv['shop_name'] = !empty($vv['shop'])?$vv['shop']['shopName']:'';
                $vv['shop_id']   = !empty($vv['shop'])?$vv['shop']['shopId']:0;
                $vv['goods_name']   = !empty($vv['goods'])?$vv['goods']['name']:0;
                $vv['service_num'] = 1;
                if(!empty($vv['nurse_one_project'])){
                    $nurse_one_project = explode(',',$vv['nurse_one_project']);
                    $nurse_one_project =  DB::name('shop_person_controls')->whereIn('id',$nurse_one_project)->column('name');
                    $vv['nurse_one_project'] = implode(',',$nurse_one_project);
                }
                if(!empty($vv['nurse_two_project'])){
                    $nurse_two_project = explode(',',$vv['nurse_two_project']);
                    $nurse_two_project =  DB::name('shop_person_controls')->whereIn('id',$nurse_two_project)->column('name');
                    $vv['nurse_one_project'] = implode(',',$nurse_two_project);
                }
                $vv['order_id'] = !empty($vv['service'])?$vv['service']['order_id']:0;

                unset($vv['shop'],$vv['nurseOne'],$vv['nurseTwo'],$vv['nurseIdOne'],$vv['nurseIdTwo'],$vv['customer'],$vv['goods']);
            }
        }
        return resultArray(['error' => '', 'data'=>['list'=>$serviceLog,'dataCount'=>$dataCount]]);

    }

    public function shopDk(): Json
    {

        $user_id = $this->userInfo['id'];

        $shopIds = $this->getCommonShopIdsCollectByUserType();

        $request = $this->param;

        $export = $request['export'] ?? 0;

        $start_time = $request['start_time'] ?? '';

        $end_time = $request['end_time'] ?? '';

        $type = $request['type'] ?? 0;

        $data= [];

        // 读取基础数据

        $year = date('Y');

        $moneth = date('m');

        $changdu    = date('t', strtotime($year."-".$moneth."-1"));

        if($start_time){

            $start_time_int = strtotime($start_time);

        }else{

            $start_time_int = strtotime($year."-".$moneth."-1");

        }

        if($end_time){

            $end_time_int = strtotime($end_time)+86399;

        }else{

            $end_time_int = strtotime($year."-".$moneth."-".$changdu)+86399;

        }


        /* 43 微信 44 抖音合作 50 高德 51 百度 52 小红书 54 抖音 55 快手 118 美团 609 抖团 56 医疗美团  597黄v */
        $xianshang = [43,44,52,54,118,609,50,55,51,56,584,597];
        // $source_id = [43,44,118,50,51,52,54,55,56,53,584];

        //$settingList = Db::name('setting')->where('category_id','=','4')->where('id','in',$xianshang)->column('name','id');

        $settingList = [

            '54'  => '抖音',
            '118' => '美团',
            '609' => '抖团',
            '43'  => '微信',
            '50'  => '高德',
            '55'  => '快手',
            '51'  => '百度',
            '52' => '小红书',
            '56'  => '医疗美团',
            '597'  => '黄V',
            '584' => '电商',
            '44' => '抖音合作',
            /* '53'  => '医疗抖音',
            '56'  => '医疗美团',
            '44'  => '医疗百度', */

        ];

        $setData = [];

        //var_dump($settingList['47']);

        unset($settingList['47']);

        unset($settingList['49']);

        $setData['online'] = $settingList;

        $setData['offline'] = [46=>'外联',47=>'门头',48=>'地推',49=>'转介绍',583=>'店转',608=>'OTC'];

        $setData['qita'] = [666=>'店转客户',667=>'加盟客户',668=>'自营客户',669=>'线上客户',670=>'渠道客户'];


        // 读取门店数据

        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;



        $shopWhere = [];

        if ($shopIds){

            array_push($shopWhere,['shop_id','in',$shopIds]);

        }
        if(!empty($type))
        {
            array_push($shopWhere,['type','=',$type]);

        }

        //array_push($shopWhere,['type','=',1]);
        array_push($shopWhere,['status','=',1]);

        array_push($shopWhere,['shop_id','not in','74076159037951,73998717474810,73782774792133']);

        $shopField = 'shop_id,shop_name,market_name';

        $shopList = Db::name('shop')

            ->where($shopWhere)

            // ->field($shopField)->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])

            ->select()->toArray();

        // $dataCount = Db::name('shop')->count();

        // if($user_id == 109){

        //     print_r($shopList[0]);exit;

        // }

        $shopIds = array_values(array_unique(array_column($shopList,'shop_id')));

        $daallList = Db::name('customer')

            ->where('shop_id','in',$shopIds)

            ->where('source_id','in',$xianshang)

            ->where('create_time','>=',$start_time_int)

            ->where('create_time','<=',$end_time_int)

            ->group('shop_id')

            ->column('count(id)','shop_id');

        $customerField = 'count(id)';

        $heji = [];

        $heji['shop_name'] = '合计';

        $heji['market_name'] = '合计';

        $heji['shop_id'] = '0';

        foreach ($shopList as $key => $val){

            // 读取每个门店的客户数据

            $onedata = [];

            $customerList = Db::name('customer')

                ->where('first_time','>','0')

                ->where('shop_id','=',$val['shop_id'])

                ->where('first_time|second_time','between',"$start_time_int,$end_time_int")

                // ->where('first_time','<=',$end_time_int)

                ->field($customerField)

                ->group('source_id')

                ->column('count(id)','source_id');


            $onedata['shop_name']    = $val['shop_name'];

            $onedata['market_name']  = $val['market_name'];

            $onlineAll = 0;

            foreach ($setData['online'] as $key1 => $val1){

                $thisonline = $customerList[$key1] ?? 0;

                $onlineAll += $thisonline;

                $onedata['online'][] = ['id'=>$key1,'num'=>$thisonline,'name'.$key1=>$thisonline];

                $heji['onlineheji'][$key1]  = isset($heji['onlineheji'][$key1]) ? bcadd($heji['onlineheji'][$key1],$thisonline):$thisonline;

                $heji['onlineheji'][$key1] = intval($heji['onlineheji'][$key1]);

                $onedata[$key1]  = $thisonline;

            }

            $onedata['onlineAll'] = $onlineAll;

            $offlineAll = 0;

            foreach ($setData['offline'] as $key2 => $val2){
                if(in_array($key2,[48])){
                    $thisoffline = $customerList[$key2] ?? 0;
                    $thisofflineOne = $customerList[663] ?? 0;
                    $thisoffline = bcadd($thisoffline,$thisofflineOne);
                }else{
                    $thisoffline = $customerList[$key2] ?? 0;
                }
                $offlineAll += $thisoffline;

                $onedata['offline'][] = ['id'=>$key1,'num'=>$thisoffline,'name'.$key1=>$thisoffline];

                $onedata[$key2]  = $thisoffline;

                $heji['offlineheji'][$key2]  = isset($heji['offlineheji'][$key2]) ? bcadd($heji['offlineheji'][$key2],$thisoffline):$thisoffline;

                $heji['offlineheji'][$key2] = intval($heji['offlineheji'][$key2]);

            }

            $onedata['offlineAll'] = $offlineAll;


            $customer_qita_list = Db::name('customer')

                ->where('first_time','>','0')

                ->where('shop_id','=',$val['shop_id'])

                ->where('first_time|second_time','between',"$start_time_int,$end_time_int")

                // ->where('first_time','<=',$end_time_int)

                ->field($customerField)

                ->group('source_type_id')

                ->column('count(id)','source_type_id');

            $qitaAll = 0;

            foreach ($setData['qita'] as $key3 => $val3){

                $thisqita = $customer_qita_list[$key3] ?? 0;

                $qitaAll += $thisqita;

                $onedata['qita'][] = ['id'=>$key3,'num'=>$thisqita,'name'.$key3=>$thisqita];

                $onedata[$key3]  = $thisqita;

                $heji['qitaheji'][$key3]  = isset($heji['qitaheji'][$key3]) ? bcadd($heji['qitaheji'][$key3],$thisqita):$thisqita;

                $heji['qitaheji'][$key3] = intval($heji['qitaheji'][$key3]);

            }

            $onedata['qitaAll'] = $qitaAll;






            $onedata['all'] =bcadd(bcadd($onlineAll,$offlineAll),$qitaAll);


            $onedata['daall'] = $daallList[$val['shop_id']] ?? 0;

            $thisBCdiv = $onedata['daall'] > 0 ? bcdiv($onlineAll,$onedata['daall'],10) : 0;

            $onedata['wljoin'] = bcmul($thisBCdiv,100,2).'%';

            $onedata['shop_id'] = $val['shop_id'];

            $data[] = $onedata;

            $heji['all']  = isset($heji['all']) ? bcadd($heji['all'],$onedata['all']):$onedata['all'];

            $heji['daall']  = isset($heji['daall']) ? bcadd($heji['daall'],$onedata['daall']):$onedata['daall'];

        }

        $heji['onlineAll'] = 0;

        foreach ($heji['onlineheji'] as $key => $val){

            $heji['online'][] = ['id'=>$key,'num'=>$val,'name'.$key1=>$val];

            $heji[$key]  = $val;

            $heji['onlineAll'] += $val;

        }

        $heji['offlineAll'] = 0;

        foreach ($heji['offlineheji'] as $key => $val){

            $heji['offline'][] = ['id'=>$key,'num'=>$val,'name'.$key1=>$val];

            $heji[$key]  = $val;

            $heji['offlineAll'] += $val;

        }

        $heji['qitaAll'] = 0;

        foreach ($heji['qitaheji'] as $key => $val){

            $heji['qita'][] = ['id'=>$key,'num'=>$val,'name'.$key1=>$val];

            $heji[$key]  = $val;

            $heji['qitaAll'] += $val;

        }

        unset($heji['onlineheji']);

        unset($heji['offlineheji']);

        unset($heji['qitaheji']);

        $heji['wljoin'] = $heji['daall']==0? '0%' :bcmul(bcdiv($heji['onlineAll'],$heji['daall'],10),100,2).'%';

        $data[] = $heji;

        $callName = [

            'market_name'   =>'店面',

            'shop_name'     =>'市场'

        ];

        $newData = [];

        foreach ($setData['online'] as $key => $val){

            $newData['online'][] = [

                'id'   => $key,

                'name' => $val

            ];

            $callName[$key] = '线上'.$val;

        }

        foreach ($setData['offline'] as $key => $val){

            $newData['offline'][] = [

                'id'   => $key,

                'name' => $val

            ];

            $callName[$key] = $val;

        }

        foreach ($setData['qita'] as $key => $val){

            $newData['qita'][] = [

                'id'   => $key,

                'name' => $val

            ];

            $callName[$key] = $val;

        }

        $callName['all'] = '总进店数量';

        $callName['daall'] = '档案数量';

        $callName['wljoin'] = '网络进店率';

        $data2              = [];

        $data2['list']      = $data ?? [];

        $data2['title']      = $newData ?? [];

        // $data2['dataCount'] = $dataCount ?? 0;

        if($export == 1){

            $downUrl = exportExcelData('线上进店统计',$callName,$data2['list'],'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

        }else{
            $data3= [];
            foreach ($data as $kye => $value)
            {
                if(empty($data3[$value['market_name']]))
                {
                    $data3[$value['market_name']]['market_name']=$value['market_name'];
                    $data3[$value['market_name']]['list']=[];
                }
                array_push($data3[$value['market_name']]['list'],$value);
            }
            $data2['list'] = [];
            foreach ($data3 as $value) {
                array_push($data2['list'], $value);
            }
            return resultArray(['error' => '', 'data'=>$data2]);
        }
    }

    public function shopDkDetail(): Json
    {

        $request = $this->param;

        // 读取门店数据

        $export = $request['export'] ?? 0;



        $where = [];

        $shop_id = $request['shop_id'] ?? 0;

        $source_id = $request['source_id'] ?? 0;

        $start_time = $request['start_time'] ?? '';

        $end_time = $request['end_time'] ?? '';

        $year = date('Y');

        $moneth = date('m');

        $changdu    = date('t', strtotime($year."-".$moneth."-1"));

        if($start_time){

            $start_time_int = strtotime($start_time);

        }else{

            $start_time_int = strtotime($year."-".$moneth."-1");

        }

        if($end_time){

            $end_time_int = strtotime($end_time);

        }else{

            $end_time_int = strtotime($year."-".$moneth."-".$changdu);

        }

        array_push($where,['first_time','>','0']);

        array_push($where,['shop_id','=',$shop_id]);

        array_push($where,['source_id','=',$source_id]);

        array_push($where,['first_time|second_time','between',"$start_time_int,$end_time_int"]);

        //array_push($where,['first_time|second_time','<=',$end_time_int]);

        $sql = Db::name('customer')->where($where);

        $dataCount = $sql->count();

        if($export == 0){

            $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

            $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

            $sql = $sql->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit']);

        }

        $list =$sql->field('customer_name,create_time,first_time,second_time,telephone,cj_money')->select()->toArray();

        $settingname = Db::name('setting')->where('id','=',$source_id)->value('name');

        foreach ($list as $key => $val){

            $list[$key]['create_time'] = date('Y-m-d H:i:s',$val['create_time']);

            $list[$key]['customer_name'] = $val['customer_name'];

            $list[$key]['telephone'] = $val['telephone'];

            $list[$key]['first_time'] =$val['second_time']>0?date('Y-m-d H:i:s',$val['second_time']): date('Y-m-d H:i:s',$val['first_time']);

            $list[$key]['cj_money'] = $val['cj_money'];

            $list[$key]['settingname'] =$settingname;

        }



        $data              = [];

        $data['list']      = $list ?? [];

        $data['dataCount'] = $dataCount ?? 0;

        if($export == 1){

            $callName = [

                    'create_time'   =>'录入时间',

                    'customer_name' =>'顾客姓名',

                    'telephone'     =>'联系方式',

                    'settingname'   =>'来源',

                    'first_time'    =>'进店时间',

                    'cj_money'      =>'成交金额（新单）'

                ];

            $downUrl = exportExcelData('线上进店明细',$callName,$data['list'],'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

        }

        return resultArray(['error' => '', 'data'=>$data]);

    }

    public function TransferIntroduction()//: Json
    {

        $request = $this->param;




		$shopIds = $this->getCommonShopIdsCollectByUserType();

        // echo "<pre>";
        // print_r($shopIds);
        // exit;

        $export = $request['export'] ?? 0;
		if($export == 0){

			$paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

			$paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
		}
        //$shop_id = $request['shop_id'] ?? 0;

        $source_id = $request['source_id'] ?? 0;

        $start_time = $request['start_time'] ?? '';

        $end_time = $request['end_time'] ?? '';

        $data= [];

        // 读取基础数据

        $year = date('Y');

        $moneth = date('m');

        $changdu    = date('t', strtotime($year."-".$moneth."-1"));

        if($start_time){

            $start_time_int = strtotime($start_time);

        }else{

            $start_time_int = strtotime($year."-".$moneth."-1");

        }

        if($end_time){

            $end_time_int = strtotime($end_time);

        }else{

            $end_time_int = strtotime($year."-".$moneth."-".$changdu);

        }

        $where = [];

        $nurse_id =  $this->userInfo['shop_person_id'];
        $nurse_id = !empty($nurse_id)?$nurse_id:0;
        $sysModel = new SysModel();
        $positon_id = $sysModel->getPersonPositionId($nurse_id);
        // 读取门店数据
        if(!empty($positon_id)){
            array_push($where,['s.introduction_id','=',$nurse_id]);
        }

        array_push($where,['s.status','=','2']);

        array_push($where,['s.is_introduction','=','1']);

        array_push($where,['s.type','=','3']);

        array_push($where,['s.deal_time','>=',$start_time_int]);

        array_push($where,['s.deal_time','<=',$end_time_int]);

        if($shopIds){
            array_push($where,['s.shop_id','in',$shopIds]);
        }



       /* $sql = Db::name('customer')->alias('cs')

            ->join('shop co', 'cs.shop_id=co.shop_id', 'LEFT')

            ->where($where); */

		$sql = Db::name('shop_refund_order')->alias('s')

		    ->join('customer c', 's.uid=c.id', 'LEFT')

		    ->where($where);


        $dataCount = $sql->count();


        if($export == 0){

            $sql = $sql->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit']);

        }

        $list = [];

        $amount = [];

        if($dataCount > 0){

            $fieldArray = [

                's.market_name',

                's.shop_name',

                'c.customer_name',

                'c.telephone',

				'c.source_id',

                'c.first_time',

                's.deal_time as cj_time',

                //'s.pay_amount*coefficient as cj_money',
				's.pay_amount as cj_money',

                's.introduction_name',

				's.introduction_id',

                'c.id as customer_id'

            ];

            $list = $sql

            ->field(implode(',',$fieldArray))

            ->order('first_time desc')

            ->select()

            ->toArray();

            $amount['cj_money'] = $sql->sum('s.pay_amount');

            $amount['market_name'] = "汇总";


           /* echo "<pre>";
            print_r($list);
            exit; */

            if($list){

                $personIds      = array_values(array_unique(array_column($list,'introduction_id')));

                $shopPersonList = Db::name('shop_person')->where('id','in',$personIds)->column('name','id');

                $customerlds = array_values(array_unique(array_column($list,'customer_id')));

                $customerScarTypeArr_zuhe    = Db::name('customer_scar')->where('customer_id', 'in', $customerlds)->column('customer_id,customer_setting_id_type');

                $customerScarTypeArr = array();

                $scarTypeIds = array_values(array_unique(array_column($customerScarTypeArr_zuhe,'customer_setting_id_type')));

                $settingIdGetNameArr = Db::name('setting')->where('id','in',$scarTypeIds)->column('name','id');

				$source_type = Db::name('setting')->where('category_id','4')->column('name','id');

                foreach ($customerScarTypeArr_zuhe as $key => $val){

                    $customerScarTypeArr[$val['customer_id']][$val['customer_setting_id_type']] = $settingIdGetNameArr[$val['customer_setting_id_type']] ?? '';

                }

                // print_r($customerScarTypeArr);exit;

                foreach ($list as $key => $val){

                    //$list[$key]['introduction_name'] = $shopPersonList[$val['introducer']] ?? '';
					$list[$key]['introduction_name'] = $val['introduction_name'] ?? '';

                    $list[$key]['introduction_money'] = bcmul($val['cj_money'],0.1,2);

                    $scar_type_position = isset($customerScarTypeArr[$val['customer_id']])?implode('、',array_values($customerScarTypeArr[$val['customer_id']])):'';

                    // print_r($scar_type_position);exit;

                    $list[$key]['scar_type_position'] = $scar_type_position;

                    $list[$key]['cj_num'] = 0;

					$list[$key]['source_name'] = $source_type[$val['source_id']];

                    $list[$key]['first_time'] =$val['first_time']>0 ? date('Y-m-d H:i:s',$val['first_time']) :'';;

                    $list[$key]['cj_time'] = date('Y-m-d H:i:s',$list[$key]['cj_time']);

                }

            }

        }

        if($export == 0){

            $data              = [];

            array_push($list,$amount);

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return resultArray(['error' => '', 'data'=>$data]);

        }else{

            $callName = [

                    'market_name'=>'市场',

                    'shop_name'=>'店面',

                    'customer_name'=>'顾客名称',

                    'telephone'=>'联系方式',

                    'scar_type_position'=>'疤痕类型',

					'source_name'=>'来源',

                    'first_time'=>'首次进店时间',

                    'cj_time'=>'成交时间',

                    'cj_money'=>'成交金额（新单）',

                    // 'cj_num'=>'成交个数',

                    'introduction_name'=>'转介绍员工',

                    'introduction_money'=>'提成金额（成交金额的10%）',

                ];

            $downUrl = exportExcelData('转介绍明细',$callName,$list,'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

        }



    }





    /**
     * 月度门店报表
     */
    public function moneth_shop_report_form()
    {
        // 获取请求参数
        $request = $this->param;
        $export = $request['export'] ?? 0;
        $start_time = $request['start_time'];
        $end_time = $request['end_time'];
        $source_type = $request['source_type'];
        // $type = $request['type'];
        // 构建查询条件
        $where = [];
        if (!empty($shopIds)) {
            $where[] = ['shop_id', 'in', $shopIds];
        }
        $where[] = ['type', '<>', 2];
        $where[] = ['status', '=', 1];
        $where[] = ['id', '<>', 219];
        // if (!empty($type)) {
        //     $where[] = ['type', '=', $type];
        // }

        // 查询店铺列表
        $shopList = Db::name('shop')
            ->where($where)
            ->where('market_id','<>',101)
            ->field('shop_id,shop_name,market_id,market_name,shop_type')
            ->select()
            ->toArray();

            $m_other_name = [];

        foreach ($shopList as &$market)
        {
            if (strpos($market["market_name"], '门诊')!== false) {
                continue;
            }
            $city = '';
            $commonCities = ['北京', '天津', '太原', '成都', '昆明', '沈阳', '济南', '石家庄', '西安', '郑州', '重庆', '长春'];
            foreach ($commonCities as $c)
            {
                if (strpos($market["market_name"], $c) === 0)
                {
                    $city = $c;
                    break;
                }
            }
            if ($city)
            {
                $newName = $city. '市场';
                $m_other_name[] = $newName;
                $market["market_name"] = $newName;
            }
        }
        unset($market);

        // 获取唯一的店铺ID数组
        $shopIds = array_values(array_unique(array_column($shopList, 'shop_id')));

        // 获取当前用户ID
        $user_id = $this->userInfo['id'];
        // 获取店铺相关数据
        $data = $this->getShopCj($shopIds, $start_time, $end_time, $user_id, $source_type);
        // var_dump($data);die;
        $ggfData = $this->shop_advertising_expense($shopIds, $start_time, $end_time);

        // 初始化返回列表和合计数据
        $returnList = [];
        $heji = [
            'market_name' => "合计",
            'shop_name' => "合计",
            'shop_task' => 0,
            'all_yuyue_num' => 0,
            'all_into_num' => 0,
            'all_bh_num' => 0,
            'all_dd_num' => 0,
            'all_xm_num' => 0,
            'all_bh_deal' => 0,
            'all_dd_deal' => 0,
            'all_xm_deal' => 0,
            'all_num_ids' => '',
            'all_deal_ids' => '',
            'all_new_order_num' => 0,
            'all_new_order_money' => 0,
            'all_order_money' => 0,
            'advertising_expenses' => 0,
            'monthROI' => 0,
            'allROI' => 0,
            'store_entry_rate' => '0%',
            'turnover_rate' => '0%'
        ];

        $hejizongyuyue = 0;
        $ggfnum = 0;

        // 遍历店铺列表，计算各项数据
        foreach ($shopList as $val)
        {
            $thisOne = [
                'market_name' => $val['market_name'],
                'shop_name' => $val['shop_name'],
                'shop_task' => $data['shoprwList'][$val['shop_id']] ?? 0,
                'all_yuyue_num' => $data['xsyyAllList'][$val['shop_id']] ?? 0,
                'all_into_num' => $data['mdjdAllList'][$val['shop_id']] ?? 0,
                'all_bh_num' => $data['bdjdAllList'][$val['shop_id']] ?? 0,
                'all_dd_num' => $data['ddjdAllList'][$val['shop_id']] ?? 0,
                'all_xm_num' => $data['xmjdAllList'][$val['shop_id']] ?? 0,
                'all_bh_deal' => $data['bdjdDealList'][$val['shop_id']] ?? 0,
                'all_dd_deal' => $data['ddjdDealList'][$val['shop_id']] ?? 0,
                'all_xm_deal' => $data['xmjdDealList'][$val['shop_id']] ?? 0,
                'all_bh_num_ids' => $data['bdjdAllList_ids'][$val['shop_id']] ?? 0,
                'all_dd_num_ids' => $data['ddjdAllList_ids'][$val['shop_id']] ?? 0,
                'all_xm_num_ids' => $data['xmjdAllList_ids'][$val['shop_id']] ?? 0,
                'all_bh_deal_ids' => $data['bdjdDealList_ids'][$val['shop_id']] ?? 0,
                'all_dd_deal_ids' => $data['ddjdDealList_ids'][$val['shop_id']] ?? 0,
                'all_xm_deal_ids' => $data['xmjdDealList_ids'][$val['shop_id']] ?? 0,
            ];

            $thisOne['all_num_ids'] = trim(implode(',', array_filter([$thisOne['all_bh_num_ids'],$thisOne['all_dd_num_ids'],$thisOne['all_xm_num_ids']])),',');
            $thisOne['all_deal_ids'] = trim(implode(',', array_filter([$thisOne['all_bh_deal_ids'],$thisOne['all_dd_deal_ids'],$thisOne['all_xm_deal_ids']])),',');

            // 计算新单成交个数和金额
            $thisCj = $data['cjAllList'][$val['shop_id']] ?? [];
            $thisOne['all_new_order_num'] = $thisCj['num'] ?? 0;
            $thisOne['all_new_order_money'] = $data['dycjAllList'][$val['shop_id']] ?? 0;

            // 计算总成交额
            $thisOne['all_order_money'] = $data['zcjAllList'][$val['shop_id']] ?? 0;

            // 计算疤痕成交率
            $thisOne['bahen_rate'] = $this->calculateRate($thisOne['all_bh_deal'], $thisOne['all_bh_num']);
            // 计算进店率和成交率
            $thisOne['store_entry_rate'] = $this->calculateRate($thisOne['all_into_num'], $thisOne['all_yuyue_num']);
            $thisOne['turnover_rate'] = $this->calculateRate($thisOne['all_new_order_num'], $thisOne['all_into_num']);

            // 获取广告费相关数据
            $scggf = $ggfData[$val['shop_id']] ?? [];
            $thisOne['advertising_expenses'] = $scggf['ggf_all'];

            // 计算当月ROI和总ROI
            $thisOne['monthROI'] = $this->calculateROI($thisOne['all_new_order_money'], $thisOne['advertising_expenses']);
            $thisOne['allROI'] = $this->calculateROI($thisOne['all_order_money'], $thisOne['advertising_expenses']);

            // 累加合计数据
            $heji['shop_task'] = bcadd($heji['shop_task'], $thisOne['shop_task']);
            $heji['all_yuyue_num'] = bcadd($heji['all_yuyue_num'], $thisOne['all_yuyue_num']);
            $heji['all_into_num'] = bcadd($heji['all_into_num'], $thisOne['all_into_num']);
            $heji['all_bh_num'] = bcadd($heji['all_bh_num'], $thisOne['all_bh_num']);
            $heji['all_dd_num'] = bcadd($heji['all_dd_num'], $thisOne['all_dd_num']);
            $heji['all_xm_num'] = bcadd($heji['all_xm_num'], $thisOne['all_xm_num']);
            $heji['all_bh_deal'] = bcadd($heji['all_bh_deal'], $thisOne['all_bh_deal']);
            $heji['all_dd_deal'] = bcadd($heji['all_dd_deal'], $thisOne['all_dd_deal']);
            $heji['all_xm_deal'] = bcadd($heji['all_xm_deal'], $thisOne['all_xm_deal']);

            $heji['all_new_order_num'] = bcadd($heji['all_new_order_num'], $thisOne['all_new_order_num']);
            $heji['all_new_order_money'] = bcadd($heji['all_new_order_money'], $thisOne['all_new_order_money']);
            $heji['all_order_money'] = bcadd($heji['all_order_money'], $thisOne['all_order_money']);
            $hejizongyuyue = bcadd($hejizongyuyue, $data['scZyyjdList'][$val['market_id']] ?? 0);
            $ggfnum = round(bcadd($ggfnum, $scggf['ggf_all'], 2));
            $returnList[] = $thisOne;
        }
        // 计算合计的广告费和ROI
        $heji['advertising_expenses'] = $ggfnum > 0 ? $ggfnum : '0.00';
        $heji['monthROI'] = $this->calculateROI($heji['all_new_order_money'], $heji['advertising_expenses']);
        $heji['allROI'] = $this->calculateROI($heji['all_order_money'], $heji['advertising_expenses']);

        // 计算合计的进店率和成交率
        $heji['store_entry_rate'] = $this->calculateRate($heji['all_into_num'], $heji['all_yuyue_num']);
        $heji['turnover_rate'] = $this->calculateRate($heji['all_new_order_num'], $heji['all_into_num']);
        $heji['bahen_rate'] = $this->calculateRate($heji['all_bh_deal'], $heji['all_bh_num']);

        // 将合计数据添加到返回列表
        $returnList[] = $heji;
        // 根据是否导出数据进行不同处理
        if ($export == 0)
        {
            $data3 = [];
            foreach ($returnList as $value)
            {
                if (empty($data3[$value['market_name']]))
                {
                    $data3[$value['market_name']] = [
                        'market_name' => $value['market_name'],
                        'list' => []
                    ];
                }
                $data3[$value['market_name']]['list'][] = $value;
            }

            $data = [
                'list' => array_values($data3),
                'dataCount' => 0
            ];

            return resultArray(['error' => '', 'data' => $data]);
        }else
        {
            $callName = [
                'market_name' => '市场名称',
                'shop_name' => '门店',
                'shop_task' => '进店目标',
                'all_yuyue_num' => '预约个数',
                'all_into_num' => '进店总数',
                'all_bh_num' => '疤痕进店',
                'all_dd_num' => '青春痘进店',
                'all_xm_num' => '项目进店',
                'store_entry_rate' => '进店率',
                'all_new_order_num' => '成交总数',
                'all_bh_deal' => '疤痕成交',
                'all_dd_deal' => '青春痘成交',
                'all_xm_deal' => '项目成交',
                'turnover_rate' => '成交率',
                'bahen_rate' => '疤痕成交率',
                'all_new_order_money' => '新单成交额',
                'all_order_money' => '总成交额',
                'advertising_expenses' => '广告费',
                'monthROI' => '新单ROI',
                'allROI' => '整体ROI'
            ];

            $downUrl = exportExcelData('月度门店报表', $callName, $returnList, 'xlsx', 1);
            return resultArray(['data' => ['url' => 'http://' . $_SERVER['HTTP_HOST'] . $downUrl], 'error' => '获取成功']);
        }
    }



    /**
     * 月度市场报表
     */
     public function moneth_market_report_form()
    {
        // 获取请求参数
        $request = $this->param;
        $export = $request['export'] ?? 0;
        $start_time = $request['start_time'];
        $end_time = $request['end_time'];
        $source_type = $request['source_type'];

        // 定义直营市场ID数组
        $zhiying = [4, 6, 7, 8, 10, 9, 11, 12, 13, 14, 16, 17, 19, 20, 21, 22, 24, 25, 23, 1, 94, 99, 101, 102, 103, 105];

        // 查询市场列表
        $where = [
            ['m.id', 'in', $zhiying]
        ];

        $shopMarketList = Db::name('shop_market')->alias('m')
            ->join('shop s', 'm.id = s.market_id')
            ->where($where)
            // ->where('s.type', 1)
            ->field('m.id as market_id, m.name as market_name')
            ->group('m.id') // 按 shop_market 表的 id 进行分组
            ->select()
            ->toArray();
            // var_dump($shopMarketList);die;
        // 为每个市场查询对应的店铺ID
        foreach ($shopMarketList as &$market) {
            $where_shop = [
                ['market_id', '=', $market['market_id']],
                ['type', '<>', 2],
                ['status', '=', 1]
            ];
            $market['shop_ids'] = Db::name('shop')
                ->where('market_id','<>',101)
                ->where($where_shop)
                ->column('shop_id');
        }
        unset($market);
        // 查询所有店铺列表
        $where = [
            ['type', '<>', 2],
            ['status', '=', 1]
        ];

        $shopList = Db::name('shop')
            ->where($where)
            ->column('market_id,shop_id');

        // 整理市场和店铺的映射关系
        $marketShopList = [];
        foreach ($shopList as $shop)
        {
            $marketShopList[$shop['market_id']][] = $shop['shop_id'];
        }

        // 获取所有店铺ID
        $shopIds = array_values(array_unique(array_column($shopList, 'shop_id')));
        // 获取店铺相关数据
        $data = $this->getShopCj($shopIds, $start_time, $end_time, '', $source_type);
        $ggfData = $this->shop_advertising_expense($shopIds, $start_time, $end_time);

        // 提取所需数据数组
        $shoprwList = $data['shoprwList'];
        $xsyyAllList = $data['xsyyAllList'];
        $scZyyjdList = $data['scZyyjdList'];
        $mdjdAllList = $data['mdjdAllList'];
        $scZmdjdList = $data['scZmdjdList'];

        $bdjdAllList = $data['bdjdAllList'];
        $ddjdAllList = $data['ddjdAllList'];
        $xmjdAllList = $data['xmjdAllList'];

        $bdjdDealList = $data['bdjdDealList'];
        $ddjdDealList = $data['ddjdDealList'];
        $xmjdDealList = $data['xmjdDealList'];

        $bdjdAllList_ids = $data['bdjdAllList_ids'];
        $ddjdAllList_ids = $data['ddjdAllList_ids'];
        $xmjdAllList_ids = $data['xmjdAllList_ids'];

        $bdjdDealList_ids = $data['bdjdDealList_ids'];
        $ddjdDealList_ids = $data['ddjdDealList_ids'];
        $xmjdDealList_ids = $data['xmjdDealList_ids'];

        $cjAllList = $data['cjAllList'];
        $dycjAllList = $data['dycjAllList'];
        $zcjAllList = $data['zcjAllList'];

        // 初始化结果列表和合计数据
        $list = [];
        $heji = [
            'market_id' => 0,
            'market_name' => '合计',
            'shop_task' => 0,
            'all_yuyue_num' => 0,
            'all_into_num' => 0,
            'all_bh_num' => 0,
            'all_dd_num' => 0,
            'all_xm_num' => 0,
            'all_bh_deal' => 0,
            'all_dd_deal' => 0,
            'all_xm_deal' => 0,
            'all_new_order_num' => 0,
            'all_new_order_money' => 0,
            'all_order_money' => 0,
            'advertising_expenses' => 0,
            'completion_rate' => '0%',
            'store_entry_rate' => '0%',
            'turnover_rate' => '0%',
            'bahen_rate' => '0%',
            'monthROI' => 0,
            'allROI' => 0
        ];

        // 遍历每个市场，先标准化市场名称，再计算各项数据
        // 标准化市场名称
        $commonCities = ['北京', '天津', '太原', '成都', '昆明', '沈阳', '济南', '石家庄', '西安', '郑州', '重庆', '长春'];


           // 遍历每个市场，计算各项数据
        foreach ($shopMarketList as $market)
        {
            $thisOne = [
                'market_id' => $market['market_id'],
                'market_name' => $market['market_name'],
                'shop_task' => 0,
                'all_yuyue_num' => $scZyyjdList[$market['market_id']] ?? 0,
                'all_into_num' => $scZmdjdList[$market['market_id']] ?? 0,
                'all_bh_num' => 0,
                'all_dd_num' => 0,
                'all_xm_num' => 0,
                'all_bh_deal' => 0,
                'all_dd_deal' => 0,
                'all_xm_deal' => 0,
                'all_bh_num_ids' => '',
                'all_dd_num_ids' => '',
                'all_xm_num_ids' => '',
                'all_bh_deal_ids' => '',
                'all_dd_deal_ids' => '',
                'all_xm_deal_ids' => '',
                'all_new_order_num' => 0,
                'all_new_order_money' => 0,
                'all_order_money' => 0,
                'advertising_expenses' => 0,
            ];

            // 计算市场的总广告费
            foreach ($market['shop_ids'] as $shopId)
            {
                $thisOne['advertising_expenses'] = bcadd($thisOne['advertising_expenses'], $ggfData[$shopId]['ggf_all'], 2);
            }

            // 计算市场的其他数据
            $thisMarketShop = $marketShopList[$market['market_id']] ?? [];
            foreach ($thisMarketShop as $shopId)
            {
                $thisCj = $cjAllList[$shopId] ?? [];
                $cjnum = $thisCj['num'] ?? 0;
                $cjmoney = $thisCj['money'] ?? 0;

                $thisOne['shop_task'] = bcadd($thisOne['shop_task'], $shoprwList[$shopId] ?? 0);
                $thisOne['all_bh_num'] = bcadd($thisOne['all_bh_num'], $bdjdAllList[$shopId] ?? 0);
                $thisOne['all_dd_num'] = bcadd($thisOne['all_dd_num'], $ddjdAllList[$shopId] ?? 0);
                $thisOne['all_xm_num'] = bcadd($thisOne['all_xm_num'], $xmjdAllList[$shopId] ?? 0);
                $thisOne['all_bh_deal'] = bcadd($thisOne['all_bh_deal'], $bdjdDealList[$shopId] ?? 0);
                $thisOne['all_dd_deal'] = bcadd($thisOne['all_dd_deal'], $ddjdDealList[$shopId] ?? 0);
                $thisOne['all_xm_deal'] = bcadd($thisOne['all_xm_deal'], $xmjdDealList[$shopId] ?? 0);

                // 字符串拼接逻辑
                if (!empty($thisOne['all_bh_num_ids'])) {
                    $thisOne['all_bh_num_ids'] .= ',';
                }
                $thisOne['all_bh_num_ids'] .= $bdjdAllList_ids[$shopId] ?? '';

                if (!empty($thisOne['all_dd_num_ids'])) {
                    $thisOne['all_dd_num_ids'] .= ',';
                }
                $thisOne['all_dd_num_ids'] .= $ddjdAllList_ids[$shopId] ?? '';

                if (!empty($thisOne['all_xm_num_ids'])) {
                    $thisOne['all_xm_num_ids'] .= ',';
                }
                $thisOne['all_xm_num_ids'] .= $xmjdAllList_ids[$shopId] ?? '';

                if (!empty($thisOne['all_bh_deal_ids'])) {
                    $thisOne['all_bh_deal_ids'] .= ',';
                }
                $thisOne['all_bh_deal_ids'] .= $bdjdDealList_ids[$shopId] ?? '';

                if (!empty($thisOne['all_dd_deal_ids'])) {
                    $thisOne['all_dd_deal_ids'] .= ',';
                }
                $thisOne['all_dd_deal_ids'] .= $ddjdDealList_ids[$shopId] ?? '';

                if (!empty($thisOne['all_xm_deal_ids'])) {
                    $thisOne['all_xm_deal_ids'] .= ',';
                }
                $thisOne['all_xm_deal_ids'] .= $xmjdDealList_ids[$shopId] ?? '';


                $thisOne['all_new_order_num'] = bcadd($thisOne['all_new_order_num'], $cjnum);
                $xd = $dycjAllList[$shopId] ?? 0;
                $thisOne['all_new_order_money'] = bcadd($thisOne['all_new_order_money'], $xd, 2);

                $zcj =$zcjAllList[$shopId] ?? 0;
                $thisOne['all_order_money'] = bcadd($thisOne['all_order_money'], $zcj, 2);
            }

            $thisOne['all_num_ids'] = trim(implode(',', array_filter([$thisOne['all_bh_num_ids'],$thisOne['all_dd_num_ids'],$thisOne['all_xm_num_ids']])),',');
            $thisOne['all_deal_ids'] = trim(implode(',', array_filter([$thisOne['all_bh_deal_ids'],$thisOne['all_dd_deal_ids'],$thisOne['all_xm_deal_ids']])),',');

            // 计算各项比率
            $thisOne['completion_rate'] = $this->calculateRate($thisOne['all_into_num'], $thisOne['shop_task']);
            $thisOne['store_entry_rate'] = $this->calculateRate($thisOne['all_into_num'], $thisOne['all_yuyue_num']);
            $thisOne['turnover_rate'] = $this->calculateRate($thisOne['all_new_order_num'], $thisOne['all_into_num']);
            $thisOne['bahen_rate'] = $this->calculateRate($thisOne['all_bh_deal'], $thisOne['all_bh_num']);

            // 计算ROI
            $thisOne['monthROI'] = $this->calculateROI($thisOne['all_new_order_money'], $thisOne['advertising_expenses']);
            $thisOne['allROI'] = $this->calculateROI($thisOne['all_order_money'], $thisOne['advertising_expenses']);

            // 累加合计数据
            $heji['shop_task'] = bcadd($heji['shop_task'], $thisOne['shop_task']);
            $heji['all_yuyue_num'] = bcadd($heji['all_yuyue_num'], $thisOne['all_yuyue_num']);
            $heji['all_into_num'] = bcadd($heji['all_into_num'], $thisOne['all_into_num']);
            $heji['all_bh_num'] = bcadd($heji['all_bh_num'], $thisOne['all_bh_num']);
            $heji['all_dd_num'] = bcadd($heji['all_dd_num'], $thisOne['all_dd_num']);
            $heji['all_xm_num'] = bcadd($heji['all_xm_num'], $thisOne['all_xm_num']);
            $heji['all_bh_deal'] = bcadd($heji['all_bh_deal'], $thisOne['all_bh_deal']);
            $heji['all_dd_deal'] = bcadd($heji['all_dd_deal'], $thisOne['all_dd_deal']);
            $heji['all_xm_deal'] = bcadd($heji['all_xm_deal'], $thisOne['all_xm_deal']);
            $heji['all_new_order_num'] = bcadd($heji['all_new_order_num'], $thisOne['all_new_order_num']);
            $heji['all_new_order_money'] = bcadd($heji['all_new_order_money'], $thisOne['all_new_order_money']);
            $heji['all_order_money'] = bcadd($heji['all_order_money'], $thisOne['all_order_money']);
            $heji['advertising_expenses'] = bcadd($heji['advertising_expenses'], $thisOne['advertising_expenses']);

            $list[] = $thisOne;
        }

        // 计算合计的各项比率和ROI
        $heji['completion_rate'] = $this->calculateRate($heji['all_into_num'], $heji['shop_task']);
        $heji['store_entry_rate'] = $this->calculateRate($heji['all_into_num'], $heji['all_yuyue_num']);
        $heji['turnover_rate'] = $this->calculateRate($heji['all_new_order_num'], $heji['all_into_num']);
        $heji['bahen_rate'] = $this->calculateRate($heji['all_bh_deal'], $heji['all_bh_num']);
        $heji['monthROI'] = $this->calculateROI($heji['all_new_order_money'], $heji['advertising_expenses']);
        $heji['allROI'] = $this->calculateROI($heji['all_order_money'], $heji['advertising_expenses']);
        // var_dump($list);die;


        //重新进行市场排序
        $commonCities = ['北京', '天津', '太原', '成都', '昆明', '沈阳', '济南', '石家庄', '西安', '郑州', '重庆', '长春'];
        $groupedMarkets = [];

        foreach ($list as $market)
        {
            $marketName = $market['market_name'];

            // 处理市场名称
            if (strpos($marketName, '门诊') !== false)
            {
                $key = $marketName;
            }elseif(strpos($marketName, '中医院') !== false)
            {
                $key = $marketName;
            }else
            {
                foreach ($commonCities as $city)
                {
                    if (strpos($marketName, $city) !== false)
                    {
                        $key = $city . '市场';
                        break;
                    }
                }
                // 未匹配到的保持原名
                $key = $key ?? $marketName;
            }
            // 初始化分组数据
            if (!isset($groupedMarkets[$key])) {
                $groupedMarkets[$key] = [
                    'market_name' => $key,
                    'shop_task' => 0,
                    'all_yuyue_num' => 0,
                    'all_into_num' => 0,
                    'all_bh_num' => 0,
                    'all_dd_num' => 0,
                    'all_xm_num' => 0,
                    'all_bh_deal' => 0,
                    'all_dd_deal' => 0,
                    'all_xm_deal' => 0,
                    'all_bh_num_ids' => '',
                    'all_dd_num_ids' => '',
                    'all_xm_num_ids' => '',
                    'all_bh_deal_ids' => '',
                    'all_dd_deal_ids' => '',
                    'all_xm_deal_ids' => '',
                    'all_new_order_num' => 0,
                    'all_new_order_money' => 0.00,
                    'all_order_money' => 0.00,
                    'advertising_expenses' => 0.00,
                    'all_num_ids' => '',
                    'all_deal_ids' => ''
                ];
            }

            // 数值字段累加
            $groupedMarkets[$key]['shop_task'] = bcadd($groupedMarkets[$key]['shop_task'], $market['shop_task'], 0);
            $groupedMarkets[$key]['all_yuyue_num'] = bcadd($groupedMarkets[$key]['all_yuyue_num'], $market['all_yuyue_num'], 0);
            $groupedMarkets[$key]['all_into_num'] = bcadd($groupedMarkets[$key]['all_into_num'], $market['all_into_num'], 0);
            $groupedMarkets[$key]['all_bh_num'] = bcadd($groupedMarkets[$key]['all_bh_num'], $market['all_bh_num'], 0);
            $groupedMarkets[$key]['all_dd_num'] = bcadd($groupedMarkets[$key]['all_dd_num'], $market['all_dd_num'], 0);
            $groupedMarkets[$key]['all_xm_num'] = bcadd($groupedMarkets[$key]['all_xm_num'], $market['all_xm_num'], 0);
            $groupedMarkets[$key]['all_bh_deal'] = bcadd($groupedMarkets[$key]['all_bh_deal'], $market['all_bh_deal'], 0);
            $groupedMarkets[$key]['all_dd_deal'] = bcadd($groupedMarkets[$key]['all_dd_deal'], $market['all_dd_deal'], 0);
            $groupedMarkets[$key]['all_xm_deal'] = bcadd($groupedMarkets[$key]['all_xm_deal'], $market['all_xm_deal'], 0);

            // ID字段拼接
            $groupedMarkets[$key]['all_bh_num_ids'] = $this->concatIds($groupedMarkets[$key]['all_bh_num_ids'], $market['all_bh_num_ids']);
            $groupedMarkets[$key]['all_dd_num_ids'] = $this->concatIds($groupedMarkets[$key]['all_dd_num_ids'], $market['all_dd_num_ids']);
            $groupedMarkets[$key]['all_xm_num_ids'] = $this->concatIds($groupedMarkets[$key]['all_xm_num_ids'], $market['all_xm_num_ids']);
            $groupedMarkets[$key]['all_bh_deal_ids'] = $this->concatIds($groupedMarkets[$key]['all_bh_deal_ids'], $market['all_bh_deal_ids']);
            $groupedMarkets[$key]['all_dd_deal_ids'] = $this->concatIds($groupedMarkets[$key]['all_dd_deal_ids'], $market['all_dd_deal_ids']);
            $groupedMarkets[$key]['all_xm_deal_ids'] = $this->concatIds($groupedMarkets[$key]['all_xm_deal_ids'], $market['all_xm_deal_ids']);

            // 金额字段处理
            $groupedMarkets[$key]['all_new_order_num'] = bcadd($groupedMarkets[$key]['all_new_order_num'], $market['all_new_order_num'], 0);
            $groupedMarkets[$key]['all_new_order_money'] = bcadd($groupedMarkets[$key]['all_new_order_money'], $market['all_new_order_money'], 2);
            $groupedMarkets[$key]['all_order_money'] = bcadd($groupedMarkets[$key]['all_order_money'], $market['all_order_money'], 2);
            $groupedMarkets[$key]['advertising_expenses'] = bcadd($groupedMarkets[$key]['advertising_expenses'], $market['advertising_expenses'], 2);
        }
        foreach ($groupedMarkets as &$group)
        {
            // 合并后的ID列表
            $group['all_num_ids'] = trim(implode(',', [
                $group['all_bh_num_ids'],
                $group['all_dd_num_ids'],
                $group['all_xm_num_ids']
            ]), ',');

            $group['all_deal_ids'] = trim(implode(',', [
                $group['all_bh_deal_ids'],
                $group['all_dd_deal_ids'],
                $group['all_xm_deal_ids']
            ]), ',');

            // 计算比率
            $group['completion_rate'] = $this->calculateRate($group['all_into_num'], $group['shop_task']);
            $group['store_entry_rate'] = $this->calculateRate($group['all_into_num'], $group['all_yuyue_num']);
            $group['turnover_rate'] = $this->calculateRate($group['all_new_order_num'], $group['all_into_num']);
            $group['bahen_rate'] = $this->calculateRate($group['all_bh_deal'], $group['all_bh_num']);

            // 计算ROI
            $group['monthROI'] = $this->calculateROI($group['all_new_order_money'], $group['advertising_expenses']);
            $group['allROI'] = $this->calculateROI($group['all_order_money'], $group['advertising_expenses']);
        }
        $list = array_values($groupedMarkets);
        $list[] = $heji;

        // 根据是否导出数据进行不同处理
        if ($export == 0)
        {
            $data = [
                'list' => $list,
                'dataCount' => 0
            ];
            return resultArray(['error' => '', 'data' => $data]);
        }else
        {
            $callName = [
                'market_name' => '市场名称',
                'shop_task' => '进店目标',
                'completion_rate' => '目标完成率',
                'all_yuyue_num' => '预约个数',
                'all_into_num' => '进店总数',
                'all_bh_num' => '疤痕进店',
                'all_dd_num' => '青春痘进店',
                'all_xm_num' => '项目进店',
                'store_entry_rate' => '进店率',
                'all_new_order_num' => '成交总数',
                'all_bh_deal' => '疤痕成交',
                'all_dd_deal' => '青春痘成交',
                'all_xm_deal' => '项目成交',
                'turnover_rate' => '成交率',
                'bahen_rate' => '疤痕成交率',
                'all_new_order_money' => '新单成交额',
                'all_order_money' => '总成交额',
                'advertising_expenses' => '广告费',
                'monthROI' => '新单ROI',
                'allROI' => '整体ROI',
            ];
            $downUrl = exportExcelData('月度市场报表', $callName, $list, 'xlsx', 1);
            return resultArray(['data' => ['url' => 'http://' . $_SERVER['HTTP_HOST'] . $downUrl], 'error' => '获取成功']);
        }
    }


    /**
     * 月度市场-门店-二级页面-用户信息
     */
    public function getMonthCustomerInfo()
    {
        // 获取请求参数
        $request = $this->param;
        $action = $request['action'] ?? '';
        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        $list = [];
        switch ($action)
        {
            case "bh_num"  :$customer_ids = $request['all_bh_num_ids']  ;break;
            case "dd_num"  :$customer_ids = $request['all_dd_num_ids']  ;break;
            case "xm_num"  :$customer_ids = $request['all_xm_num_ids']  ;break;
            case "bh_deal" :$customer_ids = $request['all_bh_deal_ids'] ;break;
            case "dd_deal" :$customer_ids = $request['all_dd_deal_ids'] ;break;
            case "xm_deal" :$customer_ids = $request['all_xm_deal_ids'] ;break;
            case "all_num" :$customer_ids = $request['all_num_ids']     ;break;
            case "all_deal":$customer_ids = $request['all_deal_ids']    ;break;
            case "chengjiao":$customer_ids = $request['chengjiao_ids']    ;break;
            default        :$customer_ids = null;
        }
        if(!empty($customer_ids))
        {
            $list = Db::name('customer')->alias('c')
                    ->distinct(true)
                    ->field('c.id, c.shop_id, c.create_time, c.customer_name, c.telephone, c.sex, m.shop_name, s.name as source_name, c.first_time, c.second_time, a.realname as operator_name, p.name as nurse_name, c.cj_time, c.cj_money')
                    ->join('setting s', 's.id = c.source_id', 'LEFT')
                    ->join('admin_user a', 'a.id = c.operator', 'LEFT')
                    ->join('shop_person p', 'p.id = c.nurse_id', 'LEFT')
                    ->join('shop m', 'm.shop_id = c.shop_id', 'LEFT')
                    ->where('c.id', 'in', $customer_ids)
                    ->paginate([
                        'list_rows' => $paging['limit'],
                        'page' => $paging['page'],
                        'query' => request()->param()
                    ])->toArray();

            if(!empty($list))
            {
                foreach($list['data'] as $key => $val)
                {
                    //疤痕类型
                    $scarList = Db::name('customer_scar')->where('customer_id','=',$val['id'])->group('customer_setting_id_type')->select()->toArray();
                    $settingList    = Db::name('setting')->column('name', 'id');
                    $scar_aggregate = '';
                    if ($scarList)
                    {
                        $typeIdArr           = array_column($scarList, 'customer_setting_id_type');
                        foreach ($typeIdArr as $typeK => $typeV)
                        {
                            $str = $settingList[$typeV] ?? '';
                            $scar_aggregate .= $str.',';
                        }
                    }
                    $list['data'][$key]['scar_aggregate']        = trim($scar_aggregate,',');

                    //时间处理
                    $list['data'][$key]['create_time'] = ($val['create_time'] != 0) ? (date('Y-m-d', $val['create_time'])?? '') : "";
                    $list['data'][$key]['first_time'] = ($val['first_time'] != 0) ? (date('Y-m-d', $val['first_time'])?? '') : "";
                    $list['data'][$key]['second_time'] = ($val['second_time'] != 0) ? (date('Y-m-d', $val['second_time'])?? '') : "";
                    $list['data'][$key]['cj_time'] = ($val['cj_time'] != 0) ? (date('Y-m-d', $val['cj_time'])?? '') : "";
                }
            }
        }
        return resultArray(['error' => '', 'data' => $list]);

    }


    //合并ID
    private function concatIds($existing, $new)
    {
        if (!empty($existing)) $existing .= ',';
        return $existing . $new;
    }

    // 计算比率的辅助函数
    private function calculateRate($numerator, $denominator)
    {
        $rate = $denominator > 0 ? bcdiv($numerator, $denominator, 4) : 0;
        return ($rate * 100) . '%';
    }

    // 计算ROI的辅助函数
    private function calculateROI($income, $cost)
    {
        return $cost > 0 ? bcdiv($income, $cost, 2) : 0;
    }






    /**
     * 月度客服进店报表
     */

    public function moneth_customer_report_form2()
    {

        $request = $this->param;

        $export  = $request['export'] ?? 0;

		$where = [];

		$userId = [945,941];

		array_push($where,['structure_id','=',8]);
		array_push($where,['id','not in',$userId]);

        //$userList= Db::name('admin_user')->where('structure_id','=','8')->column('realname,id');
		$userList= Db::name('admin_user')->where($where)->column('realname,id');
		/* echo '<pre>';
		print_r($userList);exit; */
        $laiyuanList = Db::name('setting')->where([['id','in',[43,44,118,50,51,52,54,55,56,53,584]]])->column('name,id');

        $laiyuanIds = array_values(array_unique(array_column($laiyuanList,'id')));

        // $laiyuanIds = [43,44,118,50,51,52.54,55,56,53];

        $list = [];

        //获取客服每个月的任务

        $start_time = $request['start_time'];

        $end_time = $request['end_time'];

        $year = date('Y');

        $moneth = date('m');

        $start_time_int = strtotime($start_time);

        $changdu    = date('t', strtotime($year."-".$moneth."-1"));

        $end_time_int = strtotime($end_time);

        $taskwhere = [];

        array_push($taskwhere,['yearmoneth','>=',date('Ym',$start_time_int)]);

        array_push($taskwhere,['yearmoneth','<=',date('Ym',$end_time_int)]);

        $taskList = Db::name('admin_user_moneth')->where($taskwhere)->column('task_num','kf_user_id');
		/* echo '<pre>';
        print_r($taskList);exit; */

        foreach ($userList as $key => $val){

            $oneThis = [];

            // print_r($key);

            // continue;

            if($export == 0){

                $oneThis['realname'] = $val['realname'];

                $oneThis['moneth_task'] = isset($taskList[$val['id']])?intval($taskList[$val['id']]):0;

            }

            $thisHj = [

                    'source_name' => '合计',//来源名称--

                    'luruzongshu' => 0,//--

                    'zhuanruzhiying'=> 0,//--

                    'zhuanrujiameng'=> 0,//--

                    'daodianzongshu'=> 0,//--

                    'chengjiaoshu'=> 0,//-

                    'chengjiaoe'=> 0,//--

                    'zhiyingzhuanchushu'=> 0,//--

                    'jiamengzhuanchushu'=> 0,

                    'zhiyingzhuanchulv'=> '0%',

                    'zhiyingjindianlv'=> '0%',

                    'jiamengjindianlv'=> '0%',

                    'chengjialv'=> '0%',

                ];

            foreach ($laiyuanList as $k => $v){

                 // 获取录入的总数\

                $whereLrzs = [];

                array_push($whereLrzs,['creator_id','=',$val['id']]);

                array_push($whereLrzs,['source_id','=',$v['id']]);

                array_push($whereLrzs,['create_time','>=',$start_time_int]);

                array_push($whereLrzs,['create_time','<=',$end_time_int]);

                $luruzongshuList = Db::name('customer')->where($whereLrzs)->column('shop_id,id') ?? [];

                // print_r($val['id']);exit;

                $luruzongshuShopIds = array_values(array_unique(array_column($luruzongshuList,'shop_id')));

                $luruzongCustomerIds = array_values(array_unique(array_column($luruzongshuList,'id')));

                $luruzongshu = count($luruzongshuList);

                $thisHj['luruzongshu'] = bcadd($thisHj['luruzongshu'],$luruzongshu);

            //     // // 转入直营

                $whereZrzy = [];

                array_push($whereZrzy,['shop_id','in',$luruzongshuShopIds]);

                array_push($whereZrzy,['type','=',1]);

                $zyShopIds = Db::name('shop')->where($whereZrzy)->column('shop_id') ?? [];

                array_push($whereLrzs,['shop_id','in',$zyShopIds]);

                $zhuanruzhiying = Db::name('customer')->where($whereLrzs)->count() ?? 0;

                $thisHj['zhuanruzhiying'] = bcadd($thisHj['zhuanruzhiying'],$zhuanruzhiying);

            //     // // 转入加盟

                $whereZrjm = [];

                array_push($whereZrjm,['shop_id','in',$luruzongshuShopIds]);

                array_push($whereZrjm,['type','=',2]);

                $jmShopIds = Db::name('shop')->where($whereZrjm)->column('shop_id') ?? [];

                array_pop($whereLrzs);

                array_push($whereLrzs,['shop_id','in',$jmShopIds]);

                $zhuanrujiameng = Db::name('customer')->where($whereLrzs)->count() ?? 0;

                $thisHj['zhuanrujiameng'] = bcadd($thisHj['zhuanrujiameng'],$zhuanrujiameng);

                // 进店总数

                array_pop($whereLrzs);

                array_push($whereLrzs,['first_time','>=',$start_time_int]);

                array_push($whereLrzs,['first_time','<=',$end_time_int]);

                $daodianzongshu = Db::name('customer')->where($whereLrzs)->count() ?? 0;

                $thisHj['daodianzongshu'] = bcadd($thisHj['daodianzongshu'],$daodianzongshu);

                // 成交总数

                array_pop($whereLrzs);

                array_pop($whereLrzs);

                array_push($whereLrzs,['cj_time','>=',$start_time_int]);

                array_push($whereLrzs,['cj_time','<=',$end_time_int]);

                $chengjiaoshuList = Db::name('customer')->where($whereLrzs)->column('cj_money') ?? 0;

                $chengjiaoshu = count($chengjiaoshuList);

                $thisHj['chengjiaoshu'] = bcadd($thisHj['chengjiaoshu'],$chengjiaoshu);

                // 成交总数

                $chengjiaoe = array_sum($chengjiaoshuList);

                $thisHj['chengjiaoe'] = bcadd($thisHj['chengjiaoe'],$chengjiaoe);

                // 直营转出

                $zhiyingysuoyouShopIds =Db::name('shop')->where('type','=',1)->column('shop_id') ?? [];

                $jiamengysuoyouShopIds =Db::name('shop')->where('type','=',2)->column('shop_id') ?? [];

                $zhiyingzhuanchulvWhere = [];

                array_push($zhiyingzhuanchulvWhere,['out_shop_id','in',$zhiyingysuoyouShopIds]);

                array_push($zhiyingzhuanchulvWhere,['in_shop_id','in',$jiamengysuoyouShopIds]);

                array_push($zhiyingzhuanchulvWhere,['customer_id','in',$luruzongCustomerIds]);

                array_push($zhiyingzhuanchulvWhere,['create_time','>=',$start_time_int]);

                array_push($zhiyingzhuanchulvWhere,['create_time','<=',$end_time_int]);

                // print_r($zhiyingzhuanchulvWhere);exit;

                $zhiyingzhuanchushu = Db::name('customer_transfer_shop')->where($zhiyingzhuanchulvWhere)->count() ?? 0;

                $thisHj['zhiyingzhuanchushu'] = bcadd($thisHj['zhiyingzhuanchushu'],$zhiyingzhuanchushu);

                // // // 加盟转出

                $jiamengzhuanchulvWhere = [];

                array_push($jiamengzhuanchulvWhere,['out_shop_id','in',$jiamengysuoyouShopIds]);

                array_push($jiamengzhuanchulvWhere,['in_shop_id','in',$zhiyingysuoyouShopIds]);

                array_push($jiamengzhuanchulvWhere,['customer_id','in',$luruzongCustomerIds]);

                array_push($zhiyingzhuanchulvWhere,['create_time','>=',$start_time_int]);

                array_push($zhiyingzhuanchulvWhere,['create_time','<=',$end_time_int]);

                $jiamengzhuanchushu = Db::name('customer_transfer_shop')->where($jiamengzhuanchulvWhere)->count() ?? 0;

                $thisHj['jiamengzhuanchushu'] = bcadd($thisHj['jiamengzhuanchushu'],$jiamengzhuanchushu);

                if($export == 0){

                    $oneThis['list'][] = [

                        'source_name' => $v['name'],//来源名称

                        'luruzongshu' => intval($luruzongshu),

                        'zhuanruzhiying'=> intval($zhuanruzhiying),

                        'zhuanrujiameng'=> intval($zhuanrujiameng),

                        'daodianzongshu'=> intval($daodianzongshu),

                        'chengjiaoshu'=> intval($chengjiaoshu),

                        'chengjiaoe'=> floatval($chengjiaoe),

                        'zhiyingzhuanchulv'=> $zhiyingzhuanchushu>0?bcmul(bcdiv($zhiyingzhuanchushu,$zhiyingzhuanchushu,2),100).'%':'0%',

                        'zhiyingjindianlv'=> $zhiyingzhuanchushu>0?bcmul(bcdiv($zhuanruzhiying,$zhiyingzhuanchushu,2),100).'%':'0%',

                        'jiamengjindianlv'=> $jiamengzhuanchushu>0?bcmul(bcdiv($zhuanrujiameng,$jiamengzhuanchushu,2),100).'%':'0%',

                        'chengjialv'=> $daodianzongshu>0?bcmul(bcdiv($chengjiaoshu,$daodianzongshu,2),100).'%':'0%',

                    ];

                }else{

                    $oneThis['list'][] = [

                        'realname'=>$val['realname'],

                        'realname'=>isset($taskList[$val['id']])?intval($taskList[$val['id']]):0,

                        'source_name' => $v['name'],//来源名称

                        'luruzongshu' => intval($luruzongshu),

                        'zhuanruzhiying'=> intval($zhuanruzhiying),

                        'zhuanrujiameng'=> intval($zhuanrujiameng),

                        'daodianzongshu'=> intval($daodianzongshu),

                        'chengjiaoshu'=> intval($chengjiaoshu),

                        'chengjiaoe'=> floatval($chengjiaoe),

                        'zhiyingzhuanchulv'=> $zhiyingzhuanchushu>0?bcmul(bcdiv($zhiyingzhuanchushu,$zhiyingzhuanchushu,2),100).'%':'0%',

                        'zhiyingjindianlv'=> $zhiyingzhuanchushu>0?bcmul(bcdiv($zhuanruzhiying,$zhiyingzhuanchushu,2),100).'%':'0%',

                        'jiamengjindianlv'=> $jiamengzhuanchushu>0?bcmul(bcdiv($zhuanrujiameng,$jiamengzhuanchushu,2),100).'%':'0%',

                        'chengjialv'=> $daodianzongshu>0?bcmul(bcdiv($chengjiaoshu,$daodianzongshu,2),100).'%':'0%',

                    ];

                }

            }

            $thisHj['zhiyingzhuanchulv'] = $thisHj['zhiyingzhuanchushu']>0?bcmul(bcdiv($thisHj['zhiyingzhuanchushu'],$thisHj['zhiyingzhuanchushu'],2),100).'%':'0%';

            $thisHj['zhiyingjindianlv'] = $thisHj['zhiyingzhuanchushu']>0?bcmul(bcdiv($thisHj['zhuanruzhiying'],$thisHj['zhiyingzhuanchushu'],2),100).'%':'0%';

            $thisHj['jiamengjindianlv'] = $thisHj['jiamengzhuanchushu']>0?bcmul(bcdiv($thisHj['zhuanrujiameng'],$thisHj['jiamengzhuanchushu'],2),100).'%':'0%';

            $thisHj['chengjialv'] = $thisHj['daodianzongshu']>0?bcmul(bcdiv($thisHj['chengjiaoshu'],$thisHj['daodianzongshu'],2),100).'%':'0%';

            $oneThis['list'][] = $thisHj;

            array_push($list,$oneThis);

        }

        // print_r($list);exit;

        if($export == 0){

            $data              = [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return resultArray(['error' => '', 'data'=>$data]);

        }else{

            // return resultArray(['error' => '暂不支持导出，开发中']);

            $callName = [

                    'realname'   =>'客服',

                    'source_name' => '来源',

                    'moneth_task' => '客服目标',

                    'luruzongshu' => '录入总数',

                    'zhuanruzhiying' => '转入直营',

                    'zhuanrujiameng' => '转入加盟',

                    'daodianzongshu' => '到店总数',

                    'chengjiaoshu' => '成交数',

                    'chengjiaoe' => '成交额',

                    'zhiyingzhuanchulv' => '直营转出率',

                    'zhiyingjindianlv' => '直营进店率',

                    'jiamengjindianlv' => '加盟进店率',

                    'chengjialv' => '成交率'

                ];

            $downUrl = exportExcelData('客服进店报表',$callName,$list,'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

        }

    }



    /**
     * 月度客服进店报表
     */

    public function moneth_customer_report_form()
    {

        $user_id = $this->userInfo['id'];

        $request = $this->param;

        $export  = $request['export'] ?? 0;

        // 获取客服列表

        //$userList= Db::name('admin_user')->where([['structure_id','=','8'],['status','<>',0]])->column('realname,id');

		$where = [];

		$userId = [945,941,550];

		array_push($where,['structure_id','=',8]);
		array_push($where,['status','<>',0]);
		array_push($where,['id','not in',$userId]);

		$userList= Db::name('admin_user')->where($where)->column('realname,id');


        $kefuIds = array_values(array_unique(array_column($userList,'id')));

        $laiyuanList = Db::name('setting')->where([['id','in',[43,44,118,50,51,52,54,55,584,609]]])->column('name,id');

        // $laiyuanIds = array_values(array_unique(array_column($laiyuanList,'id')));

        // 获取直营店的shop_id

        $zhiyingShopList = Db::name('shop')->where([['type','<>',2],['shop_id','<>',74076159037951]])->column('shop_id');

        // 获取加盟店的shop_id

        $jiamengShopList = Db::name('shop')->where([['type','=',2]])->column('shop_id');

        // $laiyuanIds = [43,44,118,50,51,52.54,55,56,53];

        $list = [];

        //获取客服在某时间段内的任务

        $start_time = $request['start_time'];

        $end_time = $request['end_time'];

        $start_time_int = strtotime($start_time);

        $end_time_int = strtotime($end_time);

        $taskwhere = [];

        array_push($taskwhere,['yearmoneth','>=',date('Ym',$start_time_int)]);

        array_push($taskwhere,['yearmoneth','<=',date('Ym',$end_time_int)]);

        $taskList = Db::name('admin_user_moneth')->where($taskwhere)->group('kf_user_id')->column('sum(task_num)','kf_user_id');



        // 按照客服组装根据每个来源获取相关数据集

        $luruzongshuList = [];

        $zhuanruzhiyingList = [];

        $zhuanrujiameng = [];

        $daodianzongshuList = [];

        $chengjiaoList = [];

        foreach ($laiyuanList as $key => $val){

            // 获取客服们某时间端内的录入数量

            $where = [];

            array_push($where,['source_id','=',$val['id']]);

            array_push($where,['operator','in',$kefuIds]);

            array_push($where,['create_time','>=',$start_time_int]);

            array_push($where,['create_time','<=',$end_time_int]);

            $Luruzongshu = Db::name('customer')->where($where)->group('operator')->column('count(id)','operator') ?? [];

            $luruzongshuList[$val['id']] = $Luruzongshu;



            // 获取转入直营

            $where = [];

            array_push($where,['source_id','=',$val['id']]);

            array_push($where,['operator','in',$kefuIds]);

            array_push($where,['create_time','>=',$start_time_int]);

            array_push($where,['create_time','<=',$end_time_int]);

            array_push($where,['shop_id','in',$zhiyingShopList]);

            $thisZhuanruzhiying = Db::name('customer')->where($where)->group('operator')->column('count(id)','operator') ?? [];

            $zhuanruzhiyingList[$val['id']] = $thisZhuanruzhiying;



            // 获取转入加盟

            $where = [];

            array_push($where,['source_id','=',$val['id']]);

            array_push($where,['operator','in',$kefuIds]);

            array_push($where,['create_time','>=',$start_time_int]);

            array_push($where,['create_time','<=',$end_time_int]);

            array_push($where,['shop_id','in',$jiamengShopList]);

            $zhuanrujiamengList = Db::name('customer')->where($where)->group('operator')->column('count(id)','operator') ?? [];

            $zhuanrujiameng[$val['id']] = $zhuanrujiamengList;



            // 到店总数

            // if ($) {

            //     // code...

            // }

            $where = [];

            array_push($where,['source_id','=',$val['id']]);

            array_push($where,['operator','in',$kefuIds]);

            // array_push($where,['first_time','>=',$start_time_int]);

            // array_push($where,['first_time','<=',$end_time_int]);

            array_push($where,['shop_id','in',$zhiyingShopList]);

            $daodianzongshu = Db::name('customer')

                            ->where($where)

                            ->where(function ($query) use ($start_time_int,$end_time_int) {

                                // print_r($customer_name_phone);exit;

                                    $firwhere = [];

                                    $twowhere = [];

                                    if($start_time_int > 0){

                                        array_push($firwhere,['first_time','>=',$start_time_int]);

                                        array_push($twowhere,['second_time','>=',$start_time_int]);

                                    }

                                    if($end_time_int > 0){

                                        array_push($firwhere,['first_time','<=',$end_time_int]);

                                        array_push($twowhere,['second_time','<=',$end_time_int]);

                                    }

                                    if(!empty($firwhere)){

                                        $query->where(function ($query) use ($firwhere){

                                            $query->where($firwhere);

                                        });

                                        $query->whereOr(function ($query) use ($twowhere){

                                            $query->where($twowhere);

                                        });

                                    }

                                })

                            ->group('operator')->column('count(id)','operator') ?? [];

            if($user_id == 109){

                // $where = [];

                // array_push($where,['source_id','in',[43,44,118,50,51,52,54,55,56,53]]);

                // array_push($where,['operator','=',524]);

                // // array_push($where,['first_time','>=',$start_time_int]);

                // // array_push($where,['first_time','<=',$end_time_int]);

                // array_push($where,['shop_id','in',$zhiyingShopList]);

                // $daodianzongshu = Db::name('customer')

                //             ->where($where)

                //             ->where(function ($query) use ($start_time_int,$end_time_int) {

                //                 // print_r($customer_name_phone);exit;

                //                     $firwhere = [];

                //                     $twowhere = [];

                //                     if($start_time_int > 0){

                //                         array_push($firwhere,['first_time','>=',$start_time_int]);

                //                         array_push($twowhere,['second_time','>=',$start_time_int]);

                //                     }

                //                     if($end_time_int > 0){

                //                         array_push($firwhere,['first_time','<=',$end_time_int]);

                //                         array_push($twowhere,['second_time','<=',$end_time_int]);

                //                     }

                //                     if(!empty($firwhere)){

                //                         $query->where(function ($query) use ($firwhere){

                //                             $query->where($firwhere);

                //                         });

                //                         $query->whereOr(function ($query) use ($twowhere){

                //                             $query->where($twowhere);

                //                         });

                //                     }

                //                 })

                //             ->group('operator')->column('count(id)','operator') ?? [];

                // print_r(Db::name('customer')->getLastSql());exit;

                // echo "<br>";

            }

            $daodianzongshuList[$val['id']] = $daodianzongshu;



            // 成交数和成交额

            $where = [];

            array_push($where,['source_id','=',$val['id']]);

            array_push($where,['operator','in',$kefuIds]);

            array_push($where,['cj_time','>=',$start_time_int]);

            array_push($where,['cj_time','<=',$end_time_int]);

            // $chengjiao = Db::name('customer')->where($where)->group('operator')->column('count(id) as num,sum(cj_money) as money,id','operator') ?? [];
            $chengjiao = Db::name('customer')->where($where)->group('operator')->column('count(id) as num,sum(cj_money) as money,group_concat(id) as chengjiao_ids', 'operator') ?? [];

            $chengjiaoList[$val['id']] = $chengjiao;



        }

        // print_r($taskList);exit;

        $returnList = [];

        foreach ($userList as $key => $val){

            $oneThis = [];

            // $oneThis['realname'] = $val['realname'];

            // $oneThis['moneth_task'] = isset($taskList[$val['id']])?intval($taskList[$val['id']]):0;

            $oneList = [];

            // 设置本初循环的客服id

            $kefuid = $val['id'];

            // 客服目标

            $mubiao = $taskList[$kefuid] ?? 0;

            $heji = [

                    'realname'    => $val['realname'], // '客服',

                    'moneth_task' => $mubiao, // '客服目标',

                    'source_name' => '合计', // '来源',

                    'luruzongshu' => 0, // '录入总数',

                    'zhuanruzhiying' => 0, // '转入直营',

                    'zhuanrujiameng' => 0, // '转入加盟',

                    'daodianzongshu' => 0, // '到店总数',

                    'chengjiaoshu'   => 0, // '成交数',

                    'chengjiaoe'     => 0, // '成交额',

                    'chengjiao_ids' => '' // '成交人员ID',

                ];

            foreach ($laiyuanList as $k => $v){

                $oneLaiyuan = [];

                // 设置本次循环的来源id

                $Laiyuanid = $v['id'];

                // 本次来源的录入总数集合

                $luruzongshu = $luruzongshuList[$Laiyuanid] ?? [];

                // 本次来源的转入总数集合

                $zhuanruzhiying = $zhuanruzhiyingList[$Laiyuanid] ?? [];

                // 本次来源的转入加盟总数集合

                $zhuanrujiameng = $zhuanrujiamengList[$Laiyuanid] ?? [];

                // 本次来源的到店总数集合

                $daodianzongshu = $daodianzongshuList[$Laiyuanid] ?? [];

                // 本次来源的成交总数集合

                $chengjiaoArr = $chengjiaoList[$Laiyuanid] ?? [];

                $chengjiao = $chengjiaoArr[$kefuid] ?? [];

                $oneLaiyuan = [

                    'realname'    => $val['realname'], // '客服',

                    'moneth_task' => $mubiao, // '客服目标',

                    'source_name' => $v['name'], // '来源',

                    'luruzongshu' => $luruzongshu[$kefuid] ?? 0, // '录入总数',

                    'zhuanruzhiying' => $zhuanruzhiying[$kefuid] ?? 0, // '转入直营',

                    'zhuanrujiameng' => $zhuanrujiameng[$kefuid] ?? 0, // '转入加盟',

                    'daodianzongshu' => $daodianzongshu[$kefuid] ?? 0, // '到店总数',

                    'chengjiaoshu'   => $chengjiao['num'] ?? 0, // '成交数',

                    'chengjiaoe'     => $chengjiao['money'] ?? 0, // '成交额',

                    'chengjiao_ids' => $chengjiao['chengjiao_ids'] ?? '' // 成交人员ID

                ];

                $oneLaiyuan['zhiyingzhuanchulv'] = $oneLaiyuan['luruzongshu'] > 0 ? bcdiv($oneLaiyuan['zhuanruzhiying'],$oneLaiyuan['luruzongshu'],2)*100 .'%' : '0%'; // '直营转出率',

                $oneLaiyuan['zhiyingjindianlv']  = $oneLaiyuan['zhuanruzhiying'] > 0 ? bcdiv($oneLaiyuan['daodianzongshu'],$oneLaiyuan['zhuanruzhiying'],2)*100 .'%' : '0%'; // '直营进店率',

                $oneLaiyuan['jiamengjindianlv']  = $oneLaiyuan['luruzongshu'] > 0 ? bcdiv($oneLaiyuan['zhuanrujiameng'],$oneLaiyuan['luruzongshu'],2)*100 .'%' : '0%'; // '加盟进店率',

                $oneLaiyuan['chengjialv']        = $oneLaiyuan['luruzongshu'] > 0 ? bcdiv($oneLaiyuan['chengjiaoshu'],$oneLaiyuan['luruzongshu'],2)*100 .'%' : '0%'; // '成交率'

                array_push($oneList,$oneLaiyuan);

                $heji['luruzongshu'] = bcadd($heji['luruzongshu'],$oneLaiyuan['luruzongshu']);

                $heji['zhuanruzhiying'] = bcadd($heji['zhuanruzhiying'],$oneLaiyuan['zhuanruzhiying']);

                $heji['zhuanrujiameng'] = bcadd($heji['zhuanrujiameng'],$oneLaiyuan['zhuanrujiameng']);

                $heji['daodianzongshu'] = bcadd($heji['daodianzongshu'],$oneLaiyuan['daodianzongshu']);

                $heji['chengjiaoshu'] = bcadd($heji['chengjiaoshu'],$oneLaiyuan['chengjiaoshu']);

                $heji['chengjiaoe'] = bcadd($heji['chengjiaoe'],$oneLaiyuan['chengjiaoe'],2);

                // 合并成交 ID 字符串
                if (!empty($oneLaiyuan['chengjiao_ids']))
                {
                    if (!empty($heji['chengjiao_ids']))
                    {
                        $heji['chengjiao_ids'] .= ',' . $oneLaiyuan['chengjiao_ids'];
                    } else {
                        $heji['chengjiao_ids'] = $oneLaiyuan['chengjiao_ids'];
                    }
                }

            }

            array_push($oneList,$heji);

            if ($export == 0) {

                $oneThis['realname'] = $val['realname'];

                $oneThis['moneth_task'] = $mubiao;

                $oneThis['list'] = $oneList;

                array_push($returnList,$oneThis);

            }else{

                foreach ($oneList as $k => $v){

                    array_push($returnList,$v);

                }

            }

        }

        // print_r($list);exit;

        if($export == 0){

            $data              = [];

            $data['list']      = $returnList ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return resultArray(['error' => '', 'data'=>$data]);

        }else{

            // return resultArray(['error' => '暂不支持导出，开发中']);

            $callName = [

                    'realname'   =>'客服',

                    'source_name' => '来源',

                    'moneth_task' => '客服目标',

                    'luruzongshu' => '录入总数',

                    'zhuanruzhiying' => '转入直营',

                    'zhuanrujiameng' => '转入加盟',

                    'daodianzongshu' => '到店总数',

                    'chengjiaoshu' => '成交数',

                    'chengjiaoe' => '成交额',

                    'zhiyingzhuanchulv' => '直营转出率',

                    'zhiyingjindianlv' => '直营进店率',

                    'jiamengjindianlv' => '加盟进店率',

                    'chengjialv' => '成交率'

                ];

            $downUrl = exportExcelData('客服进店报表',$callName,$returnList,'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

        }

    }



    /**
     * 门店月度任务录入
     */
    public function moneth_shop_task()
    {

        try{

            $request = $this->param;

            $where = [

                ['shop_id','=',$request['shop_id']],

                ['type','=',$request['type']]??0,

                ['year','=',$request['year']],

                ['moneth','=',$request['moneth']]

            ];

            $res = Db::name('shop_moneth')->where($where)->find();

            if($res){

                $id = $res['id'];
                $task_num_old = $res['task_num'];
                $task_num_new = $request['task_num'];

                $update_where = [];
                array_push($update_where,['id','=',$id]);

                $upDate = [
                    'task_num' => bcadd($task_num_old,$task_num_new),
                ];

                Db::name('shop_moneth')->where($update_where)->update($upDate);

                return resultArray(['error' => '调整成功']);

            }else{

                $addData['create_time'] = time();

                $addData['user_id']     = $this->userInfo['id'] ?? 0;  // 添加人id

                $addData['shop_id']     = $request['shop_id'] ?? 0;    // 店铺id

                $addData['type']     = $request['type'] ?? 0;    // 类型 : 0暂无 1网络渠道 2门头外联 3转介绍 4医疗

                $addData['task_num']    = $request['task_num'] ?? 0;   // 任务数量

                $addData['year']        = $request['year'] ?? 0;       // 年份

                $addData['moneth']      = $request['moneth'] ?? 0;     // 月份

                $addData['yearmoneth']  = $addData['year'].$addData['moneth'];     // 月份

                //$addData['advertising_expenses'] = $request['advertising_expenses'] ?? 0; // 当月广告费用

                if($addData['shop_id'] == 0 || $addData['task_num'] == 0 || $addData['year'] == 0 || $addData['moneth'] == 0 || $addData['type'] == 0){

                    return resultArray(['error' => '缺少必要参数']);

                }

                // $addData['the_last_day']         = date('t', strtotime($addData['year']."-".$addData['moneth']."-1"));

                $id = Db::name('shop_moneth')->insertGetId($addData);

                return resultArray(['error' => '任务添加成功','data'=>['id'=>$id]]);

            }




        } catch (\Exception $e) {

            return resultArray(['error' => '添加失败']);

        }

    }




    /**
     * 客服月度任务录入
     */
    public function moneth_kf_task()
    {

        try{

            $request = $this->param;

            $where = [

                    ['kf_user_id','=',$request['kf_user_id']],

                    ['year','=',$request['year']],

                    ['moneth','=',$request['moneth']]

                ];

            $res = Db::name('admin_user_moneth')->where($where)->find();

            if($res){
                $id = $res['id'];
                $task_num_old = $res['task_num'];
                $task_num_new = $request['task_num'];

                $update_where = [];
                array_push($update_where,['id','=',$id]);

                $upDate = [
                    'task_num' => bcadd($task_num_old,$task_num_new),
                ];

                Db::name('admin_user_moneth')->where($update_where)->update($upDate);

                // echo "update";exit;
                return resultArray(['error' => '调整成功']);
            }else{
                $addData['create_time'] = time();

                $addData['user_id']     = $this->userInfo['id'] ?? 0;  // 添加人id

                $addData['kf_user_id']  = $request['kf_user_id'] ?? 0;    // 客服user_id

                $addData['task_num']    = $request['task_num'] ?? 0;   // 任务数量

                $addData['year']        = $request['year'] ?? 0;       // 年份

                $addData['moneth']      = $request['moneth'] ?? 0;     // 月份

                $addData['yearmoneth']      = $addData['year'].$addData['moneth'];     // 月份

                if($addData['kf_user_id'] == 0 || $addData['task_num'] == 0 || $addData['year'] == 0 || $addData['moneth'] == 0){

                    return resultArray(['error' => '缺少必要参数']);

                }

                $id = Db::name('admin_user_moneth')->insertGetId($addData);

                return resultArray(['error' => '任务添加成功','data'=>['id'=>$id]]);

            }





        } catch (\Exception $e) {

            return resultArray(['error' => '添加失败']);

        }

    }




    /**
     * 门店月度广告费
     */
    public function moneth_mk_task()
    {
        try{

            $request = $this->param;

            $where = [

                ['shop_market_id','=',$request['shop_market_id']],

                ['year','=',$request['year']],

                ['moneth','=',$request['moneth']],

            ];

            $res = Db::name('shop_market_moneth')->where($where)->find();

            if($res){
                $id = $res['id'];
                $advertising_expenses_old = $res['advertising_expenses'];
                $advertising_expenses_new = $request['advertising_expenses'];

                $update_where = [];
                array_push($update_where,['id','=',$id]);

                $upDate = [
                    'advertising_expenses' => bcadd($advertising_expenses_old,$advertising_expenses_new),
                ];

                Db::name('shop_market_moneth')->where($update_where)->update($upDate);

                return resultArray(['error' => '调整成功']);

            }else{

                $addData['create_time'] = time();

                $addData['kf_user_id']     = $this->userInfo['id'] ?? 0;  // 添加人id

                $addData['advertising_expenses']    = $request['advertising_expenses'] ?? 0;   // 广告费

                $addData['year']        = $request['year'] ?? 0;       // 年份

                $addData['moneth']      = $request['moneth'] ?? 0;     // 月份

                $addData['yearmoneth']      = $addData['year'].$addData['moneth'] ?? 0;     // 月份

                $addData['shop_market_id']      = $request['shop_market_id'] ?? 0;     // 门店id

                if($addData['kf_user_id'] == 0 ||  $addData['year'] == 0 || $addData['moneth'] == 0){

                    return resultArray(['error' => '缺少必要参数']);

                }

                $id = Db::name('shop_market_moneth')->insertGetId($addData);

                return resultArray(['error' => '任务添加成功','data'=>['id'=>$id]]);
            }


        } catch (\Exception $e) {

            return resultArray(['error' => '添加失败']);

        }

    }



    // 获取门店相关数据统计

    public function getShopCj(array $shopIds=[],$start_time = '',$end_time = '',$user_id=0 , $source_type)
    {
        $type = '0';
        //判断来源大类
        if($source_type == 'mendian')
        {
            $xianshang = [43,44,50,51,52,54,55,118,584,609];//微信,抖音合作,高德,百度,小红书,抖音,快手,美团,本地推,抖团
            $type = '1';
        }elseif($source_type == 'mentou')
        {
            $xianshang = [46,47,48,654];//门头,外联,地铁,站点
            $type = '2';
        }elseif($source_type == 'jieshao')
        {
            $xianshang = [49];//转介绍
            $type = '3';
        }elseif($source_type == 'yiliao')
        {
            $xianshang = [597,663,56];//黄V,爱甲,医疗美团
            $type = '4';
        }elseif($source_type == 'xinxi')
        {
            $xianshang = [51,54,52,43,44];//百度,抖音,小红书,微信,抖音合作
            $type = '1';
        }elseif($source_type == 'tuangou')
        {
            $xianshang = [118,50,55];//美团,高德,快手
            $type = '1';
        }elseif($source_type == 'bendi')
        {
            $xianshang = [609,584];//抖团,本地推
            $type = '1';
        }elseif($source_type == 'all')
        {
            $xianshang = [43,44,46,47,48,49,50,51,52,53,54,55,56,118,583,584,597,608,609,653,654,663,665];
            $type = '1,2,3,4';
        }else
        {
            $xianshang = $source_type;
            if (in_array($xianshang, [43,44,50,51,52,54,55,118,584,609]))
            {
                $type = '1';
            }elseif(in_array($xianshang, [46,47,48,654]))
            {
                $type = '2';
            }elseif(in_array($xianshang, [49]))
            {
                $type = '3';
            }elseif(in_array($xianshang, [597,663,56]))
            {
                $type = '4';
            }
        }

		// echo '<pre>';
		// print_r($xianshang);exit;
        $returnData = [];

        if(empty($start_time) || empty($end_time)){
            return $returnData;
        }

        $start_time_int = strtotime($start_time);
        $end_time_int = strtotime($end_time.' 23:59:59');

        // $source_id = Db::name('setting')->where('id','in',$xianshang)->column('id');

        // 获取所需要门店的月度任务
        $start_time_ym = date('Ym',$start_time_int);
        $end_time_ym = date('Ym',$end_time_int);
        $where = [];
        array_push($where,['yearmoneth','>=',$start_time_ym]);
        array_push($where,['yearmoneth','<=',$end_time_ym]);
        array_push($where,['type','in',$type]);
        $shoprwList =  Db::name('shop_moneth')->where($where)->group('shop_id')->column('sum(task_num)','shop_id');

        //获取市场广告费
        $start_time_ym = date('Ym',$start_time_int);
        $end_time_ym = date('Ym',$end_time_int);
        $where = [];
        array_push($where,['yearmoneth','>=',$start_time_ym]);
        array_push($where,['yearmoneth','<=',$end_time_ym]);
        $scggfList =  Db::name('shop_market_moneth')->where($where)->group('shop_market_id')->column('sum(advertising_expenses)','shop_market_id');


        // 获取门店线上预约的总数
        $where = [];
        array_push($where,['create_time','>=',$start_time_int]);
        array_push($where,['create_time','<=',$end_time_int]);
        array_push($where,['shop_id','in',$shopIds]);
        array_push($where,['source_id','in',$xianshang]);
        $xsyyAllList = Db::name('customer')->where($where)->group('shop_id')->column('count(id)','shop_id');

        //var_dump($xsyyAllList);

        // 获取每个市场的预约总数
        $scList = Db::name('shop_market')->column('name,id');
        $where = [];
        array_push($where,['shop_id','in',$shopIds]);
        $shopList = Db::name('shop')->where($where)->column('market_id,shop_id');
        $scZyyjdList = [];
        foreach($scList as $key => $val){
            $count = 0;
            foreach($shopList as $k => $v){
                if($v['market_id'] == $val['id']){
                    $num = $xsyyAllList[$v['shop_id']] ?? 0;
                    $count = bcadd($count,$num);
                }
            }
            $scZyyjdList[$val['id']] = $count;
        }

        // print_r($scZyyjdList);exit;

        // print_r($xsyyAllList);exit;

		/* 获取 黄V 来源到院数据 */

        // 获取门店进店的总数

        $where = [];
        array_push($where,['first_time','>=',$start_time_int]);
        array_push($where,['first_time','<=',$end_time_int]);
        // array_push($where,['shop_id','in',$shopIds]);
        $whereOr = [];
        array_push($whereOr,['second_time','>=',$start_time_int]);
        array_push($whereOr,['second_time','<=',$end_time_int]);
        // array_push($whereOr,['shop_id','in',$shopIds]);
        $mdjdAllList = Db::name('customer')
                        ->where([['source_id','in',$xianshang]])
                        ->where([['shop_id','in',$shopIds]])
                        ->where(function($query) use ($where,$whereOr) {
                                $query -> where(function($query) use ($where) {
                                    $query -> where($where);
                                });
                                $query -> whereOr(function($query) use ($whereOr) {
                                    $query -> where($whereOr);
                                });
                            })
                        ->group('shop_id')->column('count(id)','shop_id');
        $scZmdjdList = [];
        foreach($scList as $key => $val)
        {
            $count = 0;
            foreach($shopList as $k => $v){
                if($v['market_id'] == $val['id']){
                    $num = $mdjdAllList[$v['shop_id']] ?? 0;
                    $count = bcadd($count,$num);
                }
            }
            $scZmdjdList[$val['id']] = $count;
        }
        // print_r(Db::name('customer')->getLastSql());exit;

        // print_r($mdjdAllList);exit;

        // 获取疤痕进店总数

        // $type = [1,2,3,4,5,6,7,8,655,656];
        $type = [1,2,3,4,5,6,7,8,655,656,698];
        $where = [];
        array_push($where,['c.first_time','>=',$start_time_int]);
        array_push($where,['c.first_time','<=',$end_time_int]);
        $whereOr = [];
        array_push($whereOr,['c.second_time','>=',$start_time_int]);
        array_push($whereOr,['c.second_time','<=',$end_time_int]);
        $bdjdAllList1 = Db::name('customer')->alias('c')
                    ->join('customer_scar cg', 'cg.customer_id=c.id', 'LEFT')
                    ->where([['c.shop_id','in',$shopIds]])
                    ->where([['c.source_id','in',$xianshang]])
                    ->where([['cg.customer_setting_id_type','in',$type]])
                    ->where(function($query) use ($where,$whereOr) {
                            $query -> where(function($query) use ($where) {
                                $query -> where($where);
                            });
                            $query -> whereOr(function($query) use ($whereOr) {
                                $query -> where($whereOr);
                            });
                        })
                    ->group('shop_id')
                    ->column('count(distinct c.id) as num, shop_id, group_concat(c.id) as ids', 'shop_id');
        $bdjdAllList = [];
        $bdjdAllList_ids = [];

        foreach ($bdjdAllList1 as $key => $val)
        {
            $bdjdAllList[$val['shop_id']] = $val['num'];
            $bdjdAllList_ids[$val['shop_id']] = $val['ids'];
        }

        // 疤痕成交数
        $where = [];
        array_push($where,['c.cj_time','>=',$start_time_int]);
        array_push($where,['c.cj_time','<=',$end_time_int]);
        $bdjdDealList1 = Db::name('customer')->alias('c')
                ->join('customer_scar cg', 'cg.customer_id=c.id', 'LEFT')
                ->where([['c.cj_money','>=',500]])
                ->where([['c.shop_id','in',$shopIds]])
                ->where([['c.source_id','in',$xianshang]])
                ->where([['cg.customer_setting_id_type','in',$type]])
                ->where($where)
                ->group('shop_id')
                ->column('count(distinct c.id) as num, shop_id, group_concat(c.id) as ids', 'shop_id');

        $bdjdDealList = [];
        $bdjdDealList_ids = [];

        foreach ($bdjdDealList1 as $key => $val)
        {
            $bdjdDealList[$val['shop_id']] = $val['num'];
            $bdjdDealList_ids[$val['shop_id']] = $val['ids'];
        }

        // 获取青春痘进店总数
        $type = [10];
        $where = [];
        array_push($where,['c.first_time','>=',$start_time_int]);
        array_push($where,['c.first_time','<=',$end_time_int]);
        $whereOr = [];
        array_push($whereOr,['c.second_time','>=',$start_time_int]);
        array_push($whereOr,['c.second_time','<=',$end_time_int]);
        $ddjdAllList1 = Db::name('customer')->alias('c')
                    ->where([['c.shop_id','in',$shopIds]])
                    ->where([['c.source_id','in',$xianshang]])
					->where([['cg.customer_setting_id_type','in',$type]])
                    ->join('customer_scar cg', 'cg.customer_id=c.id', 'LEFT')
                    ->where(function($query) use ($where,$whereOr) {
                            $query -> where(function($query) use ($where) {
                                $query -> where($where);
                            });
                            $query -> whereOr(function($query) use ($whereOr) {
                                $query -> where($whereOr);
                            });
                        })
                    ->group('shop_id')
                    ->column('count(distinct c.id) as num, shop_id, group_concat(c.id) as ids', 'shop_id');
        $ddjdAllList = [];
        $ddjdAllList_ids = [];

        foreach ($ddjdAllList1 as $key => $val)
        {
            $ddjdAllList[$val['shop_id']] = $val['num'];
            $ddjdAllList_ids[$val['shop_id']] = $val['ids'];
        }

        // 青春痘成交数
        $where = [];
        array_push($where,['c.cj_time','>=',$start_time_int]);
        array_push($where,['c.cj_time','<=',$end_time_int]);
        $ddjdDealList1 = Db::name('customer')->alias('c')
                    ->where([['c.cj_money','>=',500]])
                    ->where([['c.shop_id','in',$shopIds]])
                    ->where([['c.source_id','in',$xianshang]])
					->where([['cg.customer_setting_id_type','in',$type]])
                    ->join('customer_scar cg', 'cg.customer_id=c.id', 'LEFT')
                    ->where($where)
                    ->group('shop_id')
                    ->column('count(distinct c.id) as num, shop_id, group_concat(c.id) as ids', 'shop_id');
        $ddjdDealList = [];
        $ddjdDealList_ids = [];

        foreach ($ddjdDealList1 as $key => $val)
        {
            $ddjdDealList[$val['shop_id']] = $val['num'];
            $ddjdDealList_ids[$val['shop_id']] = $val['ids'];
        }

        // 获取项目进店总数
        // $type = [9,11,12];
        $type = [9,11,12,674,675];
        $where = [];
        array_push($where,['c.first_time','>=',$start_time_int]);
        array_push($where,['c.first_time','<=',$end_time_int]);
        $whereOr = [];
        array_push($whereOr,['c.second_time','>=',$start_time_int]);
        array_push($whereOr,['c.second_time','<=',$end_time_int]);
        $xmjdAllList1 = Db::name('customer')->alias('c')
                    ->join('customer_scar cg', 'cg.customer_id=c.id', 'LEFT')
                    ->where([['c.source_id','in',$xianshang]])
                    ->where([['cg.customer_setting_id_type','in',$type]])
                    ->where(function($query) use ($where,$whereOr) {
                            $query -> where(function($query) use ($where) {
                                $query -> where($where);
                            });
                            $query -> whereOr(function($query) use ($whereOr) {
                                $query -> where($whereOr);
                            });
                        })
                    ->group('shop_id')
                    ->column('count(distinct c.id) as num, shop_id, group_concat(c.id) as ids', 'shop_id');

        $xmjdAllList = [];
        $xmjdAllList_ids = [];

        foreach ($xmjdAllList1 as $key => $val)
        {
            $xmjdAllList[$val['shop_id']] = $val['num'];
            $xmjdAllList_ids[$val['shop_id']] = $val['ids'];
        }

        // 项目成交数
        $where = [];
        array_push($where,['c.cj_time','>=',$start_time_int]);
        array_push($where,['c.cj_time','<=',$end_time_int]);
        $xmjdDealList1 = Db::name('customer')->alias('c')
                    ->join('customer_scar cg', 'cg.customer_id=c.id', 'LEFT')
                    ->where([['c.cj_money','>=',500]])
                    ->where([['c.source_id','in',$xianshang]])
                    ->where([['cg.customer_setting_id_type','in',$type]])
                    ->where($where)
                    ->group('shop_id')
                    ->column('count(distinct c.id) as num, shop_id, group_concat(c.id) as ids', 'shop_id');

        $xmjdDealList = [];
        $xmjdDealList_ids = [];

        foreach ($xmjdDealList1 as $key => $val)
        {
            $xmjdDealList[$val['shop_id']] = $val['num'];
            $xmjdDealList_ids[$val['shop_id']] = $val['ids'];
        }

        // 获取成交个数
        $where = [];
        array_push($where,['cj_time','>=',$start_time_int]);
        array_push($where,['cj_time','<=',$end_time_int]);
        array_push($where,['shop_id','in',$shopIds]);
        array_push($where,['source_id','in',$xianshang]);
        array_push($where,['cj_money','>=',500]);
        $cjAllList = Db::name('customer')->where($where)->group('shop_id')->column('count(id) as num,sum(cj_money) as money','shop_id');
        // 获取总成交额
        $zcjAllList = [];
        foreach($shopIds as &$ids)
        {
            $zcjAllList[$ids] = $this->getShopNewOrderAmount($ids, $start_time_int, $end_time_int, $xianshang,$order_type = 0);
        }
        //获取本月成交额
        $dycjAllList = [];
        foreach($shopIds as &$ids)
        {
            $dycjAllList[$ids] = $this->getShopNewOrderAmount($ids, $start_time_int, $end_time_int, $xianshang,$order_type = 1);
        }


        $returnData = [

                'shoprwList' =>$shoprwList,  // 门店任务
                'xsyyAllList'=>$xsyyAllList, // 门店线上预约进店总数
                'scZyyjdList'=>$scZyyjdList, // 市场预约进店总数
                'mdjdAllList'=>$mdjdAllList, // 门店进店总数
                'scZmdjdList'=>$scZmdjdList, // 门店进店总数
                'bdjdAllList'=>$bdjdAllList, // 疤痘进店总数1
                'ddjdAllList'=>$ddjdAllList, // 青春痘进店总数1
                'xmjdAllList'=>$xmjdAllList, // 项目进店总数1
                'bdjdDealList'=>$bdjdDealList, // 疤痘成交总数1
                'ddjdDealList'=>$ddjdDealList, // 青春痘成交总数1
                'xmjdDealList'=>$xmjdDealList, // 项目成交总数1
                'bdjdAllList_ids'=>$bdjdAllList_ids, // 疤痘进店总数ids
                'ddjdAllList_ids'=>$ddjdAllList_ids, // 青春痘进店总数ids
                'xmjdAllList_ids'=>$xmjdAllList_ids, // 项目进店总数ids
                'bdjdDealList_ids'=>$bdjdDealList_ids, // 疤痘成交总数ids
                'ddjdDealList_ids'=>$ddjdDealList_ids, // 青春痘成交总数ids
                'xmjdDealList_ids'=>$xmjdDealList_ids, // 项目成交总数ids
                'cjAllList'  =>$cjAllList,   // 成交金额和成交个数总计
                'dycjAllList'=>$dycjAllList,   // 当月成交额
                'zcjAllList' =>$zcjAllList,   // 总成交金额
                'scZyyjdList'=>$scZyyjdList,   // 市场总预约
                'scggfList'  =>$scggfList,   // 市场广告费
            ];
        return $returnData;

    }

    public function getShopNewOrderAmount($shopId, $startTime, $endTime, $xianshang,$order_type = 0)
    {
		$where = [];
		array_push($where, ['type', '<>', '2']);//只有直营店数据
		array_push($where, ['status', '=', '1']);//门店关闭状态
		array_push($where, ['shop_id', 'in', (string)$shopId]);
		$shopList = Db::name('shop')->where($where)->column('shop_id,shop_name,shop_type,market_id');
		$totalNewAmount = 0;
		$totalRepairAmount = 0;
        $shopIds = array_column($shopList,"shop_id");

        $xd_amount = $bd_amount =  [];
        $newsXDMoneyAll = $budanMoneyAll = $newsXDMoneyAllOne =  $newsXDMoneyAllTwo =  $budanMoneyAllOne = $budanMoneyAllTwo = [];
        $nine_start_time = 1725120000; //24年9月1日 0：00：00
        if( $startTime >= $nine_start_time && $endTime > $nine_start_time )
        {
            //走一批
            if($order_type == 1) //新单
            {
                $mzXDMoneyAllOne = $this->outpatientPerform($shopIds,1,$startTime,$endTime,$xianshang); //门诊新单业绩
                $shopXDMoneyAllOne = $this->shopPerform($shopIds,1,$startTime,$endTime,$xianshang);  //门店新单业绩
            }else
            {
                $mzXDMoneyAllOne = $this->outpatientPerform($shopIds,1,$startTime,$endTime,$xianshang); //门诊新单业绩
                $mzBDMoneyAllTwo = $this->outpatientPerform($shopIds,2,$startTime,$endTime,$xianshang); //门诊补单业绩
                $shopXDMoneyAllOne = $this->shopPerform($shopIds,1,$startTime,$endTime,$xianshang);  //门店新单业绩
                $shopBDMoneyAllTwo = $this->shopPerform($shopIds,2,$startTime,$endTime,$xianshang);  //门店补单业绩
            }
        }else
        {
            $shopBDMoneyAllTwo = $shopXDMoneyAllOne = $mzBDMoneyAllTwo = $mzXDMoneyAllOne =[];
            if( $startTime < $nine_start_time && $endTime > $nine_start_time)
            {
                //走两批
                if($order_type == 1) //新单
                {
                    $mzXDMoneyAllOne = $this->outpatientPerform($shopIds, 1, $nine_start_time, $endTime,$xianshang); //门诊新单业绩
                    $shopBDMoneyAllTwo = $this->shopPerform($shopIds, 1, $nine_start_time, $endTime,$xianshang);//门店补单业绩

                }else
                {
                    $mzXDMoneyAllOne = $this->outpatientPerform($shopIds, 1, $nine_start_time, $endTime,$xianshang); //门诊新单业绩
                    $mzBDMoneyAllTwo = $this->outpatientPerform($shopIds, 2, $nine_start_time, $endTime,$xianshang); //门诊补单业绩
                    $shopXDMoneyAllOne = $this->shopPerform($shopIds, 2, $nine_start_time, $endTime,$xianshang);//门店新单业绩
                    $shopBDMoneyAllTwo = $this->shopPerform($shopIds, 1, $nine_start_time, $endTime,$xianshang);//门店补单业绩

                }
                $endTime = 1725119999; //24年8月31日 23 59 59
            }
            if($order_type == 1) //新单
            {
                $newsXDMoneyAll =$this->sumShopPayMoneyNewMZAll('XD',$shopIds,$startTime,$endTime,$xianshang);
                $newsXDMoneyAllOne =$this->sumShopPayMoneyNewAll('XD',$shopIds,1,$startTime,$endTime,$xianshang);
                $newsXDMoneyAllTwo =$this->sumShopPayMoneyNewAll('XD',$shopIds,2,$startTime,$endTime,$xianshang);

            }else
            {
                $newsXDMoneyAll =$this->sumShopPayMoneyNewMZAll('XD',$shopIds,$startTime,$endTime,$xianshang);
                $budanMoneyAll =$this->sumShopPayMoneyNewMZAll('BD',$shopIds,$startTime,$endTime,$xianshang);
                $newsXDMoneyAllOne =$this->sumShopPayMoneyNewAll('XD',$shopIds,1,$startTime,$endTime,$xianshang);
                $newsXDMoneyAllTwo =$this->sumShopPayMoneyNewAll('XD',$shopIds,2,$startTime,$endTime,$xianshang);
                $budanMoneyAllOne =$this->sumShopPayMoneyNewAll('BD',$shopIds,1,$startTime,$endTime,$xianshang);
                $budanMoneyAllTwo =$this->sumShopPayMoneyNewAll('BD',$shopIds,2,$startTime,$endTime,$xianshang);
            }
        }
        // var_dump($shopList);die;
        foreach ($shopList as $key=>$value)
        {
            //旧的计算规则
             if($value['market_id'] == 8 || $value['market_id'] == 9 || $value['market_id'] == 10|| $value['market_id'] == 11)
             {
                 $newsXDMoney1 = !isset($newsXDMoneyAll[$value['shop_id']])?0:$newsXDMoneyAll[$value['shop_id']];
                 $budanMoney1 = !isset($budanMoneyAll[$value['shop_id']])?0:$budanMoneyAll[$value['shop_id']];

                 array_push($xd_amount,$newsXDMoney1);
                 array_push($bd_amount,$budanMoney1);

             }else{
                 if($value['shop_type'] == 1)
                 {
                     $newsXDMoney2 = !isset($newsXDMoneyAllOne[$value['shop_id']])?0:$newsXDMoneyAllOne[$value['shop_id']];
                     $budanMoney2 = !isset($budanMoneyAllOne[$value['shop_id']])?0:$budanMoneyAllOne[$value['shop_id']];
                 }else{
                     $newsXDMoney2 = !isset($newsXDMoneyAllTwo[$value['shop_id']])?0:$newsXDMoneyAllTwo[$value['shop_id']];
                     $budanMoney2 = !isset($budanMoneyAllTwo[$value['shop_id']])?0:$budanMoneyAllTwo[$value['shop_id']];
                 }
                 array_push($xd_amount,$newsXDMoney2);
                 array_push($bd_amount,$budanMoney2);
             }
            //新的计算规则
            if ($value['shop_type'] == 1) {
                //门诊
                $newsXDMoney = !isset($mzXDMoneyAllOne[$value['shop_id']]) ? 0 : $mzXDMoneyAllOne[$value['shop_id']];
                $budanMoney = !isset($mzBDMoneyAllTwo[$value['shop_id']]) ? 0 : $mzBDMoneyAllTwo[$value['shop_id']];

            } else {
                //门店
                $newsXDMoney = !isset($shopXDMoneyAllOne[$value['shop_id']]) ? 0 : $shopXDMoneyAllOne[$value['shop_id']];
                $budanMoney = !isset($shopBDMoneyAllTwo[$value['shop_id']]) ? 0 : $shopBDMoneyAllTwo[$value['shop_id']];
            }

            array_push($xd_amount,$newsXDMoney);
            array_push($bd_amount,$budanMoney);

        }
        $totalNewAmount = array_sum($xd_amount);
        $totalRepairAmount = array_sum($bd_amount);

        $list = bcadd($totalNewAmount,$totalRepairAmount,2);
		return $list;

	}

	public function outpatientPerform($shopIds,$order_type,$startTime,$endTime,$xianshang)
	{
        $public_where=[
            ['r.status','=','2'],
            ['r.order_type','=',$order_type],
        ];

        if(!empty($shopIds)){
            array_push($public_where,['r.shop_id','in',$shopIds]);
        }
        $where = [
            ['r.refund_type','=','101.02'],
            ['r.type','=','3'],
        ];
        //收款单
        $receipt = $this->Seventeen($public_where,$where,$startTime,$endTime,$xianshang);
        //退款单
        $where = [
            ['r.refund_type','<>','101.03'],
            ['r.type','=','1'],
        ];
        $refundOrder = $this->Seventeen($public_where,$where,$startTime,$endTime,$xianshang);

        $data = [];
        foreach($receipt as $value)
        {
            $data[$value['shop_id']]=$value['pay_amount'];
        }
        foreach($refundOrder as $value)
        {
            if(empty($data[$value['shop_id']]))
            {
                $data[$value['shop_id']] = bcsub(0,$value['pay_amount'],2);
            }else{
                $data[$value['shop_id']] = bcsub($data[$value['shop_id']],$value['pay_amount'],2);
            }
        }
        return $data;

    }

    public function shopPerform($shopIds,$order_type,$startTime,$endTime,$xianshang)
    {
        $public_map = $public_where= [
            ['r.status','=','2'],
        ];
        if(in_array($order_type,[1,2])){
            array_push($public_where,['r.order_type','=',$order_type]);
            array_push($public_map,['r.order_type','=',$order_type]);
        }
        if(!empty($shopIds)){
            array_push($public_where,['r.referral_shop_id','in',$shopIds]);
            array_push($public_map,['r.shop_id','in',$shopIds]);
        }
        //12-7、收款单中订单类型新单/补单 - 疤痕/项目/护肤品/青春痘  结算方式：非店转 转诊门店是本店 取店转账号的金额
        $where =[
            ['r.type','=','3'],
            ['g.refund_mode','<>','06'],
            ['r.refund_type','=','101.02'],
        ];

        $twelve = $this->twelveToFifteen($public_where,$where,$startTime,$endTime,$xianshang);
        //13-8、收款单中 订单类型：新单/补单 -  疤痕/项目/护肤品/青春痘   结算方式：店转   转诊门店是本店 取店转账号的金额;
        $where =[
            ['r.type','=','3'],
            ['g.refund_mode','=','06'],
            ['r.refund_type','=','101.02'],
        ];
        $thirteen = $this->twelveToFifteen($public_where,$where,$startTime,$endTime,$xianshang);

        //14-9、退款单中 订单类型：新单/补单 -  疤痕/项目/护肤品/青春痘  结算方式：非店转  转诊门店是本店 取店转账号的金额 ；
        $where =[
            ['r.type','=','1'],
            ['g.refund_mode','<>','06'],
            ['r.refund_type','<>','101.03'],
        ];
        $fourteen = $this->twelveToFifteen($public_where,$where,$startTime,$endTime,$xianshang);

        //15-10、退款单中 订单类型：新单/补单 -  疤痕/项目/护肤品/青春痘  结算方式：店转 转诊门店是本店 取店转账号的金额 ；
        $where =[
            ['r.type','=','1'],
            ['g.refund_mode','=','06'],
            ['r.refund_type','<>','101.03'],
        ];
        $fifteen = $this->twelveToFifteen($public_where,$where,$startTime,$endTime,$xianshang);
        /*
        * 16/11 收款单中 收款类型：收款，且收款方式：不含店转 且订单类型: 新单/补单 -  疤痕/项目/护肤品/青春痘  的收款本金合计
         * 【减去】
         * 退款单中 退款类型：退款 退款方式：不含店转 且订单类型：新单/补单 - 疤痕/项目/护肤品/青春痘  退款本金合计 的差额即为实收业绩；
        */
        $sixteen = $this->sixteen($shopIds,$order_type,$startTime,$endTime,$xianshang);

        //18-19、退款单中  结算方式：店转  取本金账户金额；
        $where =[
            ['r.type','=','1'],
            ['g.refund_mode','=','06'],
            ['r.refund_type','<>','101.03'],

        ];
        $seventeen = $this->Seventeen($public_map,$where,$startTime,$endTime,$xianshang);
        $data = [];
        foreach($twelve as $value)
        {
            $data[$value['referral_shop_id']]['proceeds_fd']=$value['pay_amount'];
        }
        foreach($thirteen as $value)
        {
            $data[$value['referral_shop_id']]['proceeds_d']=$value['pay_amount'];
        }
        foreach($fourteen as $value)
        {
            $data[$value['referral_shop_id']]['refund_fd']=$value['pay_amount'];
        }
        foreach($fifteen as $value)
        {
            $data[$value['referral_shop_id']]['refund_d']=$value['pay_amount'];
        }
        foreach($sixteen as $key=> $value)
        {
            $data[$key]['sixteen']=$value;
        }
        foreach($seventeen as $value)
        {
            $data[$value['shop_id']]['refund_bj']=$value['pay_amount'];
        }

        foreach($data as $key => $value)
        {
            if(!isset($value['proceeds_fd']))
            {
                $data[$key]['proceeds_fd']=0;
            }
            if(!isset($value['proceeds_d']))
            {
                $data[$key]['proceeds_d']=0;
            }
            if(!isset($value['refund_fd']))
            {
                $data[$key]['refund_fd']=0;
            }
            if(!isset($value['refund_d']))
            {
                $data[$key]['refund_d']=0;
            }
            if(!isset($value['sixteen']))
            {
                $data[$key]['sixteen']=0;
            }
            if(!isset($value['refund_bj']))
            {
                $data[$key]['refund_bj']=0;
            }
        }
        $result=[];
        foreach($data as $key =>$value)
        {
            $result[$key] = round(($value['proceeds_fd']+$value['proceeds_d'] -$value['refund_fd']+$value['refund_d']+$value['sixteen']-$value['refund_bj']),2);
        }

        return  $result;
    }

    public function twelveToFifteen($public_where,$where,$startTime,$endTime,$xianshang)
    {
        $twelve = Db::name('shop_refund_order')->alias('r')
            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->field('sum(g.shop_transfer_price) as pay_amount,r.referral_shop_id')
            ->where($public_where)
            ->where($where)
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('r.deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('r.deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('r.deal_time');
            })
            ->group('r.referral_shop_id')->select()->toArray();

        return $twelve;
    }

    public function sixteen($shopIds,$order_type,$startTime,$endTime,$xianshang)
    {
        $public_where=[
            ['r.status','=','2'],
            ['g.refund_mode','<>','06'],
        ];
        if(in_array($order_type,[1,2])){
            array_push($public_where,['r.order_type','=',$order_type]);
        }
        if(!empty($shopIds)){
            array_push($public_where,['r.shop_id','in',$shopIds]);
        }
        $where = [
            ['r.refund_type','=','101.02'],
            ['r.type','=','3']
        ];
        //收款单
        $sixteen_proceeds = Db::name('shop_refund_order')->alias('r')
            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->field('sum(g.pay_price) as pay_amount,r.shop_id')
            ->where($public_where)
            ->where($where)
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('r.deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('r.deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('r.deal_time');
            })
            ->group('r.shop_id')->select()->toArray();

        //退款单
        $where = [
            ['r.refund_type','<>','101.03'],
            ['r.type','=','1']
        ];
        $sixteen_refund = Db::name('shop_refund_order')->alias('r')
            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->field('sum(g.pay_price) as pay_amount,r.shop_id')
            ->where($public_where)
            ->where($where)
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('r.deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('r.deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('r.deal_time');
            })
            ->group('r.shop_id')->select()->toArray();


        $data = [];
        foreach($sixteen_proceeds as $value)
        {
            $data[$value['shop_id']]=$value['pay_amount'];
        }
        foreach($sixteen_refund as $value)
        {
            if(empty($data[$value['shop_id']]))
            {
                $data[$value['shop_id']] = bcsub(0,$value['pay_amount'],2);
            }else{
                $data[$value['shop_id']] = bcsub($data[$value['shop_id']],$value['pay_amount'],2);
            }
        }
        return $data;
    }

    public function Seventeen($public_where,$where,$startTime,$endTime,$xianshang)
    {
        $three = Db::name('shop_refund_order')->alias('r')
            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->field('sum(g.pay_price) as pay_amount,r.shop_id')
            ->where($public_where)
            ->where($where)
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('r.deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('r.deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('r.deal_time');
            })
            ->group('r.shop_id')->select()->toArray();
        return $three;
    }

    public function sumShopPayMoneyNewMZAll($scene,$shopIds,$startTime,$endTime,$xianshang)
    {
        $where = [];
		switch ($scene) {
			case 'XD':
                array_push($where,['r.order_type','=','1']);
				break;
		    case 'BD':
                array_push($where,['r.order_type','=','2']);
				break;
		    default:
		        break;
		}
        if(!empty($shopIds))
        {
            array_push($where,['r.shop_id','in',$shopIds]);
        }
		//收款单 收款类型是 收款 且不含收款方式不是店转的
        $receive = Db::name('shop_refund_order')->alias('r')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->field('sum(r.pay_amount) as pay_amount,r.shop_id')
            ->where($where)
            ->where('r.id', 'IN', function ($query) {
                $query->table('xy_shop_refund_order_goods')->where('refund_mode', '<>', '06')->field('order_id');
            })
            ->where('r.type', '=', '3')
            ->where('r.status', '=', '2')
            ->where('r.refund_type', '=', '101.02')
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('deal_time');
            })
            ->group('r.shop_id')->select()->toArray();
		//退款单
        $refund = Db::name('shop_refund_order')->alias('r')
            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->field('sum(r.pay_amount) as pay_amount,r.shop_id')
            ->where('g.refund_mode', '<>', '06')
            ->where('r.type', '=', '1')
            ->where('r.status', '=', '2')
            ->where('r.refund_type', '=', '101.02')
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('deal_time');
            })
            ->group('r.shop_id')->select()->toArray();

        $data = [];
		foreach($receive as $value)
		{
			$data[$value['shop_id']]=$value['pay_amount'];
		}
		foreach($refund as $value)
		{
			if(empty($data[$value['shop_id']]))
			{
				$data[$value['shop_id']] = $value['pay_amount'];
			}else{
				$data[$value['shop_id']] -= $value['pay_amount'];
			}
		}
		return $data;
	}

	public function sumShopPayMoneyNewAll($scene,$shopIds,$shop_type,$startTime,$endTime,$xianshang)
    {
		$where = [];
        $wheret = [];
		switch ($scene) {
			case 'XD':
                array_push($where,['order_type','=','1']);
                array_push($wheret,['r.order_type','=','1']);
				break;
		    case 'BD':
                array_push($where,['order_type','=','2']);
                array_push($wheret,['r.order_type','=','2']);
				break;
		    default:
		        break;
		}
        if(!empty($shopIds))
        {
            array_push($wheret,['r.shop_id','in',$shopIds]);
        }
		//收款单中的疤痕业绩 不含店转的业绩--01
        $receive = Db::name('shop_refund_order')->alias('r')
            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->where($wheret)
            ->where('g.refund_mode', '<>', '06')
            ->where('r.type', '=', '3')
            ->where('r.status', '=', '2')
            ->where('r.refund_type', '=', '101.02')
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('deal_time');
            })
            ->group('r.shop_id')
            ->column('sum(g.pay_price) as pay_amount','r.shop_id');

		//退款单中的疤痕业绩	--不含店转的业绩  --02
        $refund = Db::name('shop_refund_order')->alias('r')
            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->where($wheret)
            ->where('g.refund_mode', '<>', '06')
            ->where('r.type', '=', '1')
            ->where('r.status', '=', '2')
            ->where('r.refund_type', '=', '101.02')
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('deal_time');
            })
            ->group('r.shop_id')
            ->column('sum(g.pay_price) as pay_amount', 'r.shop_id');


	    if(!empty($shopIds))
        {
            $whered = array_merge($where,[['referral_shop_id','in',$shopIds]]);
        }else{
            $whered = $where;
        }
		//门诊转店到 门店的 通过门店的归属ID 查询	--收款单 --03
        $receive_zd = Db::name('shop_refund_order')
            ->alias('r')
            ->join('customer c', 'r.uid = c.id', 'LEFT')
            ->where($whered)
            ->where('r.type', '=', '3')
            ->where('r.status', '=', '2')
            ->where('r.refund_type', '=', '101.02')
            ->whereIn('c.source_id', $xianshang)
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('r.deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('r.deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('r.deal_time');
            })
            ->group('r.referral_shop_id')
            ->column('sum(r.pay_amount * coefficient) as pay_amount', 'r.referral_shop_id');
            // var_dump($receive_zd);die;
        //退款单是店转的 疤痕/项目业绩查询  --04
        $refund_dz = Db::name('shop_refund_order')->alias('r')
        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
        ->join('customer c', 'r.uid = c.id', 'LEFT') // 关联 customer 表
        ->where($wheret)
        ->where('g.refund_mode', '=', '06')
        ->where('r.type', '=', '1')
        ->where('r.status', '=', '2')
        ->where('r.refund_type', '<>', '101.03')
        ->whereIn('c.source_id', $xianshang) // 判断 customer 的 source_id 是否在 $xianshang 中
        ->when($startTime ?? 0, function ($query) use ($startTime) {
            return $query->whereTime('r.deal_time', '>=', $startTime);
        })
        ->when($endTime ?? 0, function ($query) use ($endTime) {
            return $query->whereTime('r.deal_time', '<=', $endTime);
        }, function ($query) use ($endTime) {
            return $query->whereMonth('r.deal_time');
        })
        ->group('r.shop_id')
        ->column('sum(g.pay_price * r.coefficient) as pay_amount', 'r.shop_id');
        // var_dump($refund_dz);die;
        //收款单是店转的 疤痕/项目业绩---05
        $receive_dz = Db::name('shop_refund_order')->alias('r')
        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
        ->join('customer c', 'r.uid = c.id', 'LEFT') // 关联 customer 表
        ->where($wheret)
        ->where('g.refund_mode', '=', '06')
        ->where('r.type', '=', '3')
        ->where('r.status', '=', '2')
        ->where('r.refund_type', '=', '101.02')
        ->whereIn('c.source_id', $xianshang) // 判断 customer 的 source_id 是否在 $xianshang 中
        ->when($startTime ?? 0, function ($query) use ($startTime) {
            return $query->whereTime('r.deal_time', '>=', $startTime);
        })
        ->when($endTime ?? 0, function ($query) use ($endTime) {
            return $query->whereTime('r.deal_time', '<=', $endTime);
        }, function ($query) use ($endTime) {
            return $query->whereMonth('r.deal_time');
        })
        ->group('r.shop_id')
        ->column('sum(g.pay_price * r.coefficient) as pay_amount', 'r.shop_id');
        // var_dump($receive_dz);die;
        if(!empty($shopIds))
        {
            $whered = array_merge($where,[['shop_id','in',$shopIds]]);
        }else
        {
            $whered = $where;
        }
        //门诊收款单 是非疗程的 疤痕/项目业绩  --06
        // 修改 $whered 数组中的 shop_id 为 r.shop_id
        foreach ($whered as &$condition) {
            if ($condition[0] === 'shop_id') {
                $condition[0] = 'r.shop_id';
            }
        }
        unset($condition); // 释放引用

        $receive_mz = Db::name('shop_refund_order')
            ->alias('r')
            ->join('customer c', 'r.uid = c.id', 'LEFT') // 关联 customer 表
            ->where($whered)
            ->where('r.is_treatment', '=', '2')
            ->where('r.type', '=', '3')
            ->where('r.referral_shop_id', '>', '0')
            ->where('r.status', '=', '2')
            ->where('r.refund_type', '<>', '101.03')
            ->whereIn('c.source_id', $xianshang) // 判断 customer 的 source_id 是否在 $xianshang 中
            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('r.deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('r.deal_time', '<=', $endTime);
            }, function ($query) use ($endTime) {
                return $query->whereMonth('r.deal_time');
            })
            ->group('r.shop_id')
            ->column('sum(r.pay_amount * coefficient) as pay_amount', 'r.shop_id');
        // var_dump($receive_mz);die;
		$data = [];
		foreach($receive as $key => $value)
		{
			$data[$key]['receive']=$value;
		}

		foreach($refund as $key => $value)
		{
			$data[$key]['refund']=$value;
		}

		foreach($receive_dz as $key => $value)
		{
			$data[$key]['receive_dz']=$value;
		}
		foreach($receive_mz as $key => $value)
		{
			$data[$key]['receive_mz']=$value;
		}
		foreach($refund_dz as $key => $value)
		{
			$data[$key]['refund_dz']=$value;
		}
		foreach($receive_zd as $key => $value)
		{
			$data[$key]['receive_zd']=$value;
		}
		foreach($data as $key => $value)
		{
			if(empty($value['refund']))
			{
				$data[$key]['refund']=0;
			}
			if(empty($value['receive']))
			{
				$data[$key]['receive']=0;
			}
			if(empty($value['receive_dz']))
			{
				$data[$key]['receive_dz']=0;
			}
			if(empty($value['receive_mz']))
			{
				$data[$key]['receive_mz']=0;
			}
			if(empty($value['refund_dz']))
			{
				$data[$key]['refund_dz']=0;
			}
			if(empty($value['receive_zd']))
			{
				$data[$key]['receive_zd']=0;
			}
		}
        $result = [];
		if($shop_type==1){ //1是门诊 2是门店
			foreach($data as $key =>$value)
			{
				$result[$key] = round(($value['receive']-$value['refund'] +$value['receive_dz']-$value['receive_mz']-$value['refund_dz']),2);
			}
		}else{
			//实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
			foreach($data as $key =>$value)
			{
				$result[$key] = round(($value['receive']-$value['refund'] +$value['receive_zd']+$value['receive_dz']-$value['refund_dz']),2);
			}
		}
		return $result;
	}






















    /**
     * 店面余额报表
     */
    public function getZyCustomer2()
    {

        ini_set('memory_limit','1024M');

        $request = $this->param;

        $export = $request['export'] ?? 0;

// 读取门店数据

        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;



        $start_time = $request['start_time'] ?? date('Y-m-d');

        $end_time = $request['end_time'] ?? date('Y-m-d');

        $start_time = '2022-01-22';

        $start_time_int = strtotime($start_time);

        $end_time_int = strtotime($end_time);

        $time     = $start_time;

        $timeInt  = strtotime($time);

        $monthDay = date('t',$timeInt);

        $zyShopList = Db::name('shop')->where('type','=',1)->column('shop_name,shop_id','shop_id');

        $shopIds = array_values(array_unique(array_column($zyShopList,'shop_id')));

        $zyCustomerList = Db::name('customer')->where('shop_id','in',$shopIds)->column('id,customer_name,shop_id,telephone','id');

        // print_r(count($zyCustomerList));exit();

        $sql = Db::name('customer_balance_tj')

                ->where('time','=',date('Ymd',$timeInt))

                ->order('customer_id desc');

        $dataCount = $sql ->count();

        // print_r($dataCount);exit;

        if($dataCount>0){

            if($export == 0){

                $sql = $sql->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit']);

            }

            $list = $sql->select()->toArray();

            // print_r($time);

            $customer_ids = array_values(array_unique(array_column($zyCustomerList,'id')));

            $orderWhere = [];

            array_push($orderWhere,['uid','in',$customer_ids]);

            array_push($orderWhere,['type','=',3]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            $shoukuan = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            $orderWhere = [];

            array_push($orderWhere,['uid','in',$customer_ids]);

            array_push($orderWhere,['type','=',1]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            $tuikuan  = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            $orderWhere = [];

            array_push($orderWhere,['uid','in',$customer_ids]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            $chuku = Db::name('shop_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            $orderWhere = [];

            array_push($orderWhere,['uid','in',$customer_ids]);

            array_push($orderWhere,['type','=',2]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            $tuiku    = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            $qichuyue = [];

            foreach ($list as $key => $val){

                $one = [];

                if(isset($qichuyue[$val['customer_id']])){

                    $one = $qichuyue[$val['customer_id']];

                }else{

                    $one['customer_name'] = $zyCustomerList[$val['customer_id']]['customer_name'] ?? '';

                    $customer = $zyCustomerList[$val['customer_id']] ?? [];

                    $shop_id  = empty($customer) ? 0 : $customer['shop_id'];

                    $shop     = $zyShopList[$shop_id] ?? [];

                    $one['shop_name']     = $shop['shop_name'] ?? '';

                    $one['telephone']     = $shop['telephone'] ?? '';

                    $one['benjin_bahen']  = '0';

                    $one['zengjin_bahen'] = '0';

                    $one['benjin_xiangmu']  = '0';

                    $one['zengjin_xiangmu'] = '0';

                    $one['qichuyue'] = '0';

                    $one['yueheji'] = '0';

                    $thisshoukuan = $shoukuan[$val['customer_id']] ?? [];

                    $thistuikuan = $tuikuan[$val['customer_id']] ?? [];

                    $shoukuanMoney = bcadd($thisshoukuan['gift_amount']??0,$thisshoukuan['pay_amount']??0,2);

                    $tuikuaMoney = bcadd($thistuikuan['gift_amount']??0,$thistuikuan['pay_amount']??0,2);

                    $one['benyueshoukuan'] = bcsub($shoukuanMoney,$tuikuaMoney,2);

                    $thischuku = $shoukuan[$val['customer_id']] ?? [];

                    $thistuiku = $tuiku[$val['customer_id']] ?? [];

                    $chukuMoney = bcadd($thischuku['gift_amount']??0,$thischuku['pay_amount']??0,2);

                    $tuikuMoney = bcadd($thistuiku['gift_amount']??0,$thistuiku['pay_amount']??0,2);

                    $one['benyuechuku'] = bcsub($chukuMoney,$tuikuMoney,2);

                }

                if ($val['balance_category_id'] == 1){

                    $one['benjin_bahen']  = $val['money'];

                    $one['zengjin_bahen'] = $val['complimentary_money'];

                    $zongji = bcadd($one['benjin_bahen'],$one['zengjin_bahen'],2);

                    $one['qichuyue'] = bcadd($one['qichuyue'],$zongji,2);

                    $one['yueheji'] = $one['qichuyue'];

                }else{

                    $one['benjin_xiangmu']  = $val['money'];

                    $one['zengjin_xiangmu'] = $val['complimentary_money'];

                    $zongji = bcadd($one['benjin_xiangmu'],$one['zengjin_xiangmu'],2);

                    $one['qichuyue'] = bcadd($one['qichuyue'],$zongji,2);

                    $one['yueheji'] = $one['qichuyue'];

                }

                $qichuyue[$val['customer_id']] = $one;

            }

            $qichuyue = array_values($qichuyue);

        }



        $data              = [];

        $data['list']      = $qichuyue ?? [];

        $data['dataCount'] = $dataCount ?? 0;

        if($export == 1){

            $callName = [

                    'customer_name'   =>'客户姓名',

                    'shop_name'       =>'门店',

                    'telephone'       =>'手机号',

                    'qichuyue'     =>'期初余额',

                    'benyueshoukuan'  =>'本月收款',

                    'benyuechuku'     =>'本月出库',

                    'benjin_bahen'    =>'疤痕本金',

                    'zengjin_bahen'   =>'疤痕赠金',

                    'benjin_xiangmu'  =>'项目本金',

                    'zengjin_xiangmu' =>'项目赠金',

                    'yueheji'      =>'余额合计'

                ];

            $downUrl = exportExcelData('店面余额报表',$callName,$data['list'],'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

        }



        return resultArray(['data'=>$data,'error'=>'处理成功']);

    }



    /**
     * 店面余额报表
     */
    public function getZyCustomer()
    {

        // 设置内存

        ini_set('memory_limit','1024M');

        set_time_limit(0);

        // 获取传入数据

        $request = $this->param;

        $export = $request['export'] ?? 0;

        // print_r($export);exit;

        // 读取门店数据

        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;



        // 初始化时间集合

        $start_time = $request['start_time'] ?? date('Y-m-d');

        $end_time = $request['end_time'] ?? date('Y-m-d');

        // $start_time = '2022-01-22';

        // $end_time = '2022-01-30';

        $start_time_int = strtotime($start_time);

        $end_time_int = strtotime($end_time) + 86399;



        // 获取门店数据

        $shopIds = $this->getCommonShopIdsCollectByUserType();

        //$shopIds = 73782774834649;//大学路

        $shopWhere = [];

        if($shopIds){

            array_push($shopWhere,['shop_id','in',$shopIds]);

        }

        array_push($shopWhere,['type','=',1]);

        $zyShopList = Db::name('shop')->where($shopWhere)->column('shop_name,shop_id','shop_id');




        // 获取客户数据

        $shopIds = array_values(array_unique(array_column($zyShopList,'shop_id')));

        // $ycCustomerIds = array_values(array_unique(array_column($ycCustomerList,'id')));// 4月7日新增

        // 获取有预存的顾客数据 4月7日新增
        $ycWhere = [];

        array_push($ycWhere,['shop_id','in',$shopIds]);

        array_push($ycWhere,['money|complimentary_money','<>','0.00']);

        $ycCustomerList = Db::name('customer_balance')->where($ycWhere)->column('customer_id');

        // echo "<pre>";
        // print_r($ycCustomerList);
        // exit;



        $sql = Db::name('customer');

        // $sql = $sql ->where('shop_id','in',$shopIds);

        $sql = $sql ->where('id','in',$ycCustomerList);// 4月7日新增

        // $sql = $sql ->where('consumption','<>','0.00');// 4月4日新增

        $dataCount = $sql->count();

        // echo $dataCount;exit;

        if($export == 0){

            $sql = $sql -> limit(($paging['page'] - 1) * $paging['limit'], $paging['limit']);

        }

        $returnList = [];

        $zyCustomerList = $sql -> column('id,customer_name,shop_id,telephone,king_no,fcustId','id');



        if($zyCustomerList){

            // 获取需要查询的期初余额数据

            $customerIds = array_keys($zyCustomerList);

            //$customerIds = 94011;

            $chushiBalanceList = Db::name('customer_balance_tj')

                                ->where('time','=',date('Ymd',$start_time_int))

                                ->where('customer_id','in',$customerIds)

                                ->select();

            $balanceList = [];

            foreach ($chushiBalanceList as $key => $val){

                $balanceList[$val['customer_id']][$val['balance_category_id']] = $val;

            }

            // echo "<pre>";
            // print_r($balanceList);exit;

            // 获取收款金额

            $orderWhere = [];

            // array_push($orderWhere,['uid','in',$customerIds]);

            array_push($orderWhere,['type','=',3]);

            array_push($orderWhere,['status','<>',3]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            array_push($orderWhere,['business_type','=',1]);

            $shoukuanbahen1 = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            $orderWhere = [];

            // array_push($orderWhere,['uid','in',$customerIds]);

            array_push($orderWhere,['type','=',2]);

            array_push($orderWhere,['status','<>',3]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            array_push($orderWhere,['business_type','=',1]);

            $shoukuanbahen2 = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

             $orderWhere = [];

            // array_push($orderWhere,['uid','in',$customerIds]);

            array_push($orderWhere,['type','=',3]);

            array_push($orderWhere,['status','<>',3]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            array_push($orderWhere,['business_type','=',2]);

            $shoukuanxiangmu1 = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            $orderWhere = [];

            // array_push($orderWhere,['uid','in',$customerIds]);

            array_push($orderWhere,['type','=',2]);

            array_push($orderWhere,['status','<>',3]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            array_push($orderWhere,['business_type','=',2]);

            $shoukuanxiangmu2 = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            // 获取消耗金额

            $orderWhere = [];

            // array_push($orderWhere,['uid','in',$customerIds]);

            array_push($orderWhere,['status','<>',4]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            array_push($orderWhere,['business_type','=',1]);

            $chukubahen1 = Db::name('shop_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            // array_push($orderWhere,['uid','in',$customerIds]);

            array_push($orderWhere,['status','<>',3]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            array_push($orderWhere,['business_type','=',1]);

            $chukubahen2 = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            $orderWhere = [];

            // array_push($orderWhere,['uid','in',$customerIds]);

            array_push($orderWhere,['status','<>',4]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            array_push($orderWhere,['business_type','=',2]);

            $chukuxiangmu1 = Db::name('shop_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            // array_push($orderWhere,['uid','in',$customerIds]);

            array_push($orderWhere,['status','<>',3]);

            array_push($orderWhere,['create_time','>=',$start_time_int]);

            array_push($orderWhere,['create_time','<=',$end_time_int]);

            array_push($orderWhere,['business_type','=',2]);

            $chukuxiangmu2 = Db::name('shop_refund_order')->where($orderWhere)->group('uid')->column('sum(gift_amount) as gift_amount,sum(pay_amount) as pay_amount ','uid');

            // print_r(321);exit;

            // 组装数据

            foreach($zyCustomerList as $key => $val){

                $thisId = $val['id'];

                $thisOne = [

                    'customer_name'   =>$val['customer_name'],

                    'shop_name'       =>isset($zyShopList[$val['shop_id']]) ? $zyShopList[$val['shop_id']]['shop_name'] : '',

                    'telephone'       =>$val['telephone'],

                    'king_no'         =>$val['king_no'],

                    'fcustId'         =>$val['fcustId'],

                    // 'qichuyue'     =>'期初余额',

                    // 'benyueshoukuan'  =>'本月收款',

                    // 'benyuechuku'     =>'本月出库',

                    // 'benjin_bahen'    =>'疤痕本金',

                    // 'zengjin_bahen'   =>'疤痕赠金',

                    // 'benjin_xiangmu'  =>'项目本金',

                    // 'zengjin_xiangmu' =>'项目赠金',

                    // 'yueheji'         =>'余额合计'

                ];

                $balance = $balanceList[$key] ?? [];

                $qcBhb = isset($balance[1]) ? $balance[1]['money'] : 0;

                $qcBhz = isset($balance[1]) ? $balance[1]['complimentary_money'] : 0;

                $qcXmb = isset($balance[2]) ? $balance[2]['money'] : 0;

                $qcXmz = isset($balance[1]) ? $balance[2]['complimentary_money'] : 0;

                // 设置期初余额

                $thisOne['qichuyue'] = bcadd(bcadd($qcBhb,$qcBhz,2),bcadd($qcXmb,$qcXmz,2),2);

                // 设置本月收入

                $shoukuanbahen1ben  = $shoukuanbahen1[$thisId]['pay_amount'] ?? 0;

                $shoukuanbahen1zeng = $shoukuanbahen1[$thisId]['gift_amount'] ?? 0;

                $shoukuanbahen2ben  = $shoukuanbahen2[$thisId] ['pay_amount']?? 0;

                $shoukuanbahen2zeng = $shoukuanbahen2[$thisId]['gift_amount'] ?? 0;

                $shoukuanxiangmu1ben  = $shoukuanxiangmu1[$thisId]['pay_amount'] ?? 0;

                $shoukuanxiangmu1zeng = $shoukuanxiangmu1[$thisId]['gift_amount'] ?? 0;

                $shoukuanxiangmu2ben  = $shoukuanxiangmu2[$thisId]['pay_amount'] ?? 0;

                $shoukuanxiangmu2zeng = $shoukuanxiangmu2[$thisId]['gift_amount'] ?? 0;

                $benyueshoukuanbahen   = bcadd(bcadd($shoukuanbahen1ben,$shoukuanbahen1zeng,2),bcadd($shoukuanbahen2ben,$shoukuanbahen2zeng,2),2);

                $benyueshoukuanxiangmu = bcadd(bcadd($shoukuanxiangmu1ben,$shoukuanxiangmu1zeng,2),bcadd($shoukuanxiangmu2ben,$shoukuanxiangmu2zeng,2),2);

                $thisOne['benyueshoukuan'] = bcadd($benyueshoukuanbahen,$benyueshoukuanxiangmu,2);

                // 设置本月出库

                $chukubahen1ben  = $chukubahen1[$thisId]['pay_amount'] ?? 0;

                $chukubahen1zeng = $chukubahen1[$thisId]['gift_amount'] ?? 0;

                $chukubahen2ben  = $chukubahen2[$thisId]['pay_amount'] ?? 0;

                $chukubahen2zeng = $chukubahen2[$thisId]['gift_amount'] ?? 0;

                $chukuxiangmu1ben  = $chukuxiangmu1[$thisId]['pay_amount'] ?? 0;

                $chukuxiangmu1zeng = $chukuxiangmu1[$thisId]['gift_amount'] ?? 0;

                $chukuxiangmu2ben  = $chukuxiangmu2[$thisId]['pay_amount'] ?? 0;

                $chukuxiangmu2zeng = $chukuxiangmu2[$thisId]['gift_amount'] ?? 0;

                $benyuechukubahen   = bcadd(bcadd($chukubahen1ben,$chukubahen1zeng,2),bcadd($chukubahen2ben,$chukubahen2zeng,2),2);

                $benyuechukuxiangmu = bcadd(bcadd($chukuxiangmu1ben,$chukuxiangmu1zeng,2),bcadd($chukuxiangmu2ben,$chukuxiangmu2zeng,2),2);

                $thisOne['benyuechuku'] = bcadd($benyuechukubahen,$benyuechukuxiangmu,2);

                // 疤痕本金剩余

                $bahenbenjinshoukuan = bcadd($shoukuanbahen1ben,$shoukuanbahen2ben,2);

                $bahenbenjintuikuan  = bcadd($chukubahen1ben,$chukubahen2ben,2);

                $thisOne['benjin_bahen'] = bcadd($qcBhb,$bahenbenjinshoukuan,2);

                $thisOne['benjin_bahen'] = bcsub($thisOne['benjin_bahen'],$bahenbenjintuikuan,2);

                // 疤痕赠金剩余

                $bahenzengjinshoukuan = bcadd($shoukuanbahen1zeng,$shoukuanbahen2zeng,2);

                $bahenzengtuikuan  = bcadd($chukubahen2zeng,$chukubahen2zeng,2);

                $thisOne['zengjin_bahen'] = bcadd($qcBhz,$bahenzengjinshoukuan,2);

                $thisOne['zengjin_bahen'] = bcsub($thisOne['zengjin_bahen'],$bahenzengtuikuan,2);

                // 项目本金剩余

                $xiangmuzengjinshoukuan = bcadd($shoukuanxiangmu1zeng,$shoukuanxiangmu2zeng,2);

                $xiangmuzengtuikuan  = bcadd($chukuxiangmu2zeng,$chukuxiangmu2zeng,2);

                $thisOne['benjin_xiangmu'] = bcadd($qcXmb,$xiangmuzengjinshoukuan,2);

                $thisOne['benjin_xiangmu'] = bcsub($thisOne['benjin_xiangmu'],$xiangmuzengtuikuan,2);

                // 项目赠金剩余

                $xiangmuzengjinshoukuan = bcadd($shoukuanxiangmu1zeng,$shoukuanxiangmu2zeng,2);

                $xiangmuzengtuikuan  = bcadd($chukuxiangmu2zeng,$chukuxiangmu2zeng,2);

                $thisOne['zengjin_xiangmu'] = bcadd($qcXmz,$xiangmuzengjinshoukuan,2);

                $thisOne['zengjin_xiangmu'] = bcsub($thisOne['zengjin_xiangmu'],$xiangmuzengtuikuan,2);

                // 获取余额合计

                $thisOne['yueheji'] = bcadd($thisOne['benjin_bahen'],$thisOne['zengjin_bahen'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['benjin_xiangmu'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['zengjin_xiangmu'],2);

                array_push($returnList,$thisOne);


            }

        }

        // print_r($returnList[0]);exit;

        // 设置返回数据组

        $data              = [];

        $data['list']      = $returnList;

        $data['dataCount'] = $dataCount ?? 0;

        if($export == 1){

            $fileName = '店面余额报表';

            $savePath= '/excel/店面余额报表.csv';

            $file_path= app()->getRootPath().'public'.$savePath;

            // header('Content-Encoding: UTF-8');

            // header("Content-type:application/vnd.ms-excel;charset=UTF-8");

            // header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');

            // $callName = [

            //         'customer_name'   =>'客户姓名',

            //         'shop_name'       =>'门店',

            //         'telephone'       =>'手机号',

            //         'qichuyue'     =>'期初余额',

            //         'benyueshoukuan'  =>'本月收款',

            //         'benyuechuku'     =>'本月出库',

            //         'benjin_bahen'    =>'疤痕本金',

            //         'zengjin_bahen'   =>'疤痕赠金',

            //         'benjin_xiangmu'  =>'项目本金',

            //         'zengjin_xiangmu' =>'项目赠金',

            //         'yueheji'      =>'余额合计'

            //     ];

            if (file_exists($file_path)) {

                unlink($file_path);

            }

            $callName = [

                    '客户姓名',

                    '门店',

                    '手机号',

                    'K3代码',

                    '顾客内码',

                    '期初余额',

                    '本月收款',

                    '本月出库',

                    '疤痕本金',

                    '疤痕赠金',

                    '项目本金',

                    '项目赠金',

                    '余额合计'

                ];

            $fp = fopen( $file_path, "a");

            $head = array_values($callName);

            $field = array_keys($callName);

            foreach ($head as $i => $v) {

                //CSV的Excel支持GBK编码，一定要转换，否则乱码

                $head[$i] = iconv("utf-8","gb2312//IGNORE",$v);

            }

            fputcsv($fp, $head);



            // //打开php标准输出流

            // $fp = fopen('php://output', 'a');



            // //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。

            // fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));

            //   //添加导出标题

            // fputcsv($fp, $callName);



            //链接数据库

            $step = bcadd(bcdiv(count($data['list']),10000),1); //循环次数

            $nums = 10000; //每次导出数量

            $list = $data['list'];

            // print_r(123);exit;

            for($i = 0; $i < $step; $i++) {

                $start = $i * 10000;

                $thiList = array_slice($list,$start,$nums);

                $thisOne = [];

                foreach ($thiList as $item) {

                    foreach($item as $n => $val){

                        $thisOne[$n] = "\t" . iconv("utf-8","gb2312//IGNORE",$val);

                    }

                    fputcsv($fp, $thisOne);

                }

                //每1万条数据就刷新缓冲区

                ob_flush();

                flush();

            }

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$savePath],'error' => '获取成功']);

            exit;

            // $downUrl = exportExcelData('店面余额报表',$callName,$data['list'],'csv',1);

            // return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

        }



        return resultArray(['data'=>$data,'error'=>'处理成功']);

    }


   /**
     * 店面余额报表
     */
    public function getZyCustomer3()
    {

        // 设置内存

        ini_set('memory_limit','1024M');

        set_time_limit(0);

        // 获取传入数据

        $request = $this->param;



        $export = $request['export'] ?? 0;

        // print_r($export);exit;

        // 读取门店数据

        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;



        // 初始化时间集合

        $start_time = $request['start_time'] ?? date('Y-m-d');

        $end_time = ($request['end_time'] > date('Y-m-d')) ? date("Y-m-d") : $request['end_time'];

        // 接收门店数据
        $shopID = $request['shop_id'] ?? '';


        $start_time_int = strtotime($start_time);

        $end_time_int = strtotime($end_time) + 86399;

		// echo '开始时间--'.$start_time_int;echo '<br/>';
		// echo '结束时间--'.$end_time_int;echo '<br/>';

        // 获取门店数据

        $shopIds = $this->getCommonShopIdsCollectByUserType();

        //$shopIds = 73782774834649;//大学路

        $shopWhere = [];

        if($shopIds){

            array_push($shopWhere,['shop_id','in',$shopIds]);

        }

        //array_push($shopWhere,['type','=',1]);
		array_push($shopWhere,['status','=',1]);

        $zyShopList = Db::name('shop')->where($shopWhere)->column('shop_name,shop_id','shop_id');

        // echo "<pre>";
        // print_r($zyShopList);
        // echo "</pre>";
        // exit;


        // 获取客户数据

        $shopIds = array_values(array_unique(array_column($zyShopList,'shop_id')));

        // $ycCustomerIds = array_values(array_unique(array_column($ycCustomerList,'id')));// 4月7日新增

        // 获取有预存的顾客数据 4月7日新增
        $ycWhere = [];

        array_push($ycWhere,['shop_id','in',$shopIds]);

        array_push($ycWhere,['money|complimentary_money|shop_transfer_money','<>','0.00']);

        array_push($ycWhere,['time','=',date('Ymd',strtotime($end_time))]);

        if($shopID){
            array_push($ycWhere,['shop_id','=',$shopID]);
        }

        $sql = Db::name('customer_balance_tj')->where($ycWhere);

        $field = ['distinct customer_id'];

        $dataCount = $sql->field($field)->count();

        if($export == 0){

            $sql = $sql -> limit(($paging['page'] - 1) * $paging['limit'], $paging['limit']);

        }

        $ycCustomerList = $sql->field($field)->select()->toArray();

        $ycCustomerList = array_values(array_unique(array_column($ycCustomerList, 'customer_id')));

        // echo "<pre>";
        // print_r($ycCustomerList);
        // exit;



        $sql = Db::name('customer');

        $sql = $sql ->where('id','in',$ycCustomerList);// 4月7日新增

        $returnList = [];

        $zyCustomerList = $sql -> column('id,customer_name,shop_id,telephone,king_no,fcustId','id');
		//$zyCustomerList = [231700];
        // echo "<pre>";
        // print_r($zyCustomerList);
        // exit;


        if($zyCustomerList){

            // 获取需要查询的期初余额数据

            $customerIds = array_keys($zyCustomerList);

            //$customerIds = 94011;

            $chushiBalanceList = Db::name('customer_balance_tj')

                                ->where('time','=',date('Ymd',strtotime($end_time)))

                                ->where('customer_id','in',$customerIds)

                                ->select();


            // echo "<pre>";
            // print_r($chushiBalanceList);
            // exit;

            $balanceList = [];

            foreach ($chushiBalanceList as $key => $val){

                $balanceList[$val['customer_id']][$val['balance_category_id']] = $val;

            }



            // 组装数据

           foreach($zyCustomerList as $key => $val){

                $thisId = $val['id'];

                $thisOne = [

                    'customer_name'   =>$val['customer_name'],

                    'shop_name'       =>isset($zyShopList[$val['shop_id']]) ? $zyShopList[$val['shop_id']]['shop_name'] : '',

                    'telephone'       =>$val['telephone'],

                    'king_no'         =>$val['king_no'],

                    'fcustId'         =>$val['fcustId'],

                ];

                $balance = $balanceList[$key] ?? [];

                $qcBhb  = isset($balance[1]) ? $balance[1]['money'] : 0;

                $qcBhz  = isset($balance[1]) ? $balance[1]['complimentary_money'] : 0;

                $qcBhd  = isset($balance[1]) ? $balance[1]['shop_transfer_money'] : 0;

                $qcXmb  = isset($balance[2]) ? $balance[2]['money'] : 0;

                $qcXmz  = isset($balance[2]) ? $balance[2]['complimentary_money'] : 0;

                $qcXmd  = isset($balance[2]) ? $balance[2]['shop_transfer_money'] : 0;


                $qcQcdb = isset($balance[3]) ? $balance[3]['money'] : 0;

                $qcQcdz = isset($balance[3]) ? $balance[3]['complimentary_money'] : 0;

                $qcQcdd  = isset($balance[3]) ? $balance[3]['shop_transfer_money'] : 0;


                $qcHfpb = isset($balance[4]) ? $balance[4]['money'] : 0;

                $qcHfpz = isset($balance[4]) ? $balance[4]['complimentary_money'] : 0;

                $qcHfpd  = isset($balance[4]) ? $balance[4]['shop_transfer_money'] : 0;



                $linshiNum = '0.00';
                // 设置期初余额

                $thisOne['qichuyue'] = bcadd($linshiNum,$linshiNum,2);

                // 设置本月收入

                $thisOne['benyueshoukuan'] = bcadd($linshiNum,$linshiNum,2);

                // 设置本月出库

                $thisOne['benyuechuku'] = bcadd($linshiNum,$linshiNum,2);

                // 疤痕本金剩余

                $thisOne['benjin_bahen'] = bcadd($qcBhb,$linshiNum,2);

                // 疤痕赠金剩余

                $thisOne['zengjin_bahen'] = bcadd($qcBhz,$linshiNum,2);

                // 疤痕赠金店转
                $thisOne['dianzhuan_bahen'] = bcadd($qcBhd,$linshiNum,2);

                // 项目本金剩余
                $thisOne['benjin_xiangmu'] = bcadd($qcXmb,$linshiNum,2);

                // 项目赠金剩余

                $thisOne['zengjin_xiangmu'] = bcadd($qcXmz,$linshiNum,2);

                // 项目赠金店转
                $thisOne['dianzhuan_xiangmu'] = bcadd($qcXmd,$linshiNum,2);


                // 青春痘本金剩余 青春痘增进剩余
                $thisOne['benjin_qingchundou'] = bcadd($qcQcdb,$linshiNum,2);
                $thisOne['zengjin_qingchundou'] = bcadd($qcQcdz,$linshiNum,2);
                $thisOne['dianzhuan_qingchundou'] = bcadd($qcQcdd,$linshiNum,2);

                // 护肤品本金剩余 护肤品增进剩余
                $thisOne['benjin_hufupin'] = bcadd($qcHfpb,$linshiNum,2);
                $thisOne['zengjin_hufupin'] = bcadd($qcHfpz,$linshiNum,2);
                $thisOne['dianzhuan_hufupin'] = bcadd($qcHfpd,$linshiNum,2);


                // 获取余额合计

                $thisOne['yueheji'] = bcadd($thisOne['benjin_bahen'],$thisOne['zengjin_bahen'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['dianzhuan_bahen'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['benjin_xiangmu'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['zengjin_xiangmu'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['dianzhuan_xiangmu'],2);


                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['benjin_qingchundou'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['zengjin_qingchundou'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['dianzhuan_qingchundou'],2);


                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['benjin_hufupin'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['zengjin_hufupin'],2);

                $thisOne['yueheji'] = bcadd($thisOne['yueheji'],$thisOne['dianzhuan_hufupin'],2);

                array_push($returnList,$thisOne);


            }

        }
		// echo '<pre>';
  //       print_r($returnList);exit;

        // 设置返回数据组

        $data              = [];

        $data['list']      = $returnList;

        $data['dataCount'] = $dataCount ?? 0;

        if($export == 1){

           $callName = [

                'customer_name'   => '客户姓名',

                'shop_name'       => '门店',

                'telephone'       => '手机号',

                'king_no'         => 'K3代码',

                'fcustId'         => '顾客内码',

                'qichuyue'        => '期初余额',

                'benyueshoukuan'  => '本月收款',

                'benyuechuku'     => '本月出库',

                'benjin_bahen'    => '疤痕本金',

                'zengjin_bahen'   => '疤痕赠金',

                'dianzhuan_bahen'   => '疤痕店转',

                'benjin_xiangmu'  => '项目本金',

                'zengjin_xiangmu' => '项目赠金',

                'dianzhuan_xiangmu' => '项目店转',

                'benjin_qingchundou'  => '青春痘本金',

                'zengjin_qingchundou' => '青春痘赠金',

                'dianzhuan_qingchundou' => '青春痘店转',

                'benjin_hufupin'  => '护肤品本金',

                'zengjin_hufupin' => '护肤品赠金',

                'dianzhuan_hufupin' => '护肤品店转',

                'yueheji'         => '余额合计'

            ];

            $excelName = '店面余额报表';

            $downUrl = exportExcelData($excelName,$callName,$returnList,'xlsx',1);
            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

            // $downUrl = exportExcelData('店面余额报表',$callName,$returnList,'xlsx',1);

            // echo "<script language='javascript'>";

            // echo " location='".$downUrl."';";

            // echo "</script>";
        }

        // if($export == 1){

        //     $fileName = '店面余额报表';

        //     $savePath= '/excel/店面余额报表.csv';

        //     $file_path= app()->getRootPath().'public'.$savePath;



        //     if (file_exists($file_path)) {

        //         unlink($file_path);

        //     }

        //     $callName = [

        //             '客户姓名',

        //             '门店',

        //             '手机号',

        //             'K3代码',

        //             '顾客内码',

        //             '期初余额',

        //             '本月收款',

        //             '本月出库',

        //             '疤痕本金',

        //             '疤痕赠金',

        //             '项目本金',

        //             '项目赠金',

        //             '余额合计'

        //         ];

        //     $fp = fopen( $file_path, "a");

        //     $head = array_values($callName);

        //     $field = array_keys($callName);

        //     foreach ($head as $i => $v) {

        //         //CSV的Excel支持GBK编码，一定要转换，否则乱码

        //         $head[$i] = iconv("utf-8","gb2312//IGNORE",$v);

        //     }

        //     fputcsv($fp, $head);



        //     // //打开php标准输出流

        //     // $fp = fopen('php://output', 'a');



        //     // //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。

        //     // fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));

        //     //   //添加导出标题

        //     // fputcsv($fp, $callName);



        //     //链接数据库

        //     $step = bcadd(bcdiv(count($data['list']),10000),1); //循环次数

        //     $nums = 10000; //每次导出数量

        //     $list = $data['list'];

        //     // print_r(123);exit;

        //     for($i = 0; $i < $step; $i++) {

        //         $start = $i * 10000;

        //         $thiList = array_slice($list,$start,$nums);

        //         $thisOne = [];

        //         foreach ($thiList as $item) {

        //             foreach($item as $n => $val){

        //                 $thisOne[$n] = "\t" . iconv("utf-8","gb2312//IGNORE",$val);

        //             }

        //             fputcsv($fp, $thisOne);

        //         }

        //         //每1万条数据就刷新缓冲区

        //         ob_flush();

        //         flush();

        //     }

        //     return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$savePath],'error' => '获取成功']);

        //     exit;

        //     // $downUrl = exportExcelData('店面余额报表',$callName,$data['list'],'csv',1);

        //     // return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

        // }



        return resultArray(['data'=>$data,'error'=>'处理成功']);

    }




    public function getPerson()
    {

        $where  = [];

        array_push($where,['status','=',1]);

        $personList = Db::name('shop_person')->where($where)->column('shop_id,shop_name,name');

        $list = [];

        foreach ($personList as $key => $val){

            $thisOne = [];

            $thisOne['name'] = $val['name'];

            $thisOne['shop_name'] = $val['shop_name'];

            $thisOne['yueyuepingfen'] = 0;

            $thisOne['huifangpingfen'] = 0;

            $thisOne['zonghedefen'] = 0;

            array_push($list,$thisOne);

        }

        $callName = [

                    'name'   =>'员工名称',

                    'shop_name'       =>'店面',

                    'yueyuepingfen'       =>'预约评价',

                    'huifangpingfen'     =>'回访评价',

                    'zonghedefen'  =>'综合得分'

                ];

        $downUrl = exportExcelData('员工评分记录',$callName,$list,'xlsx',1);

        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

    }




    // 新广告费计算公式
    public function shop_advertising_expense($shopIds,$start_time_int,$end_time_int)
    {

        // echo "<pre>";
        // print_r($shopIds);
        // echo "</pre>";

        // echo "开始时间：".$start_time_int;
        // echo "<br/>";

        // echo "结束时间：".$end_time_int;
        // echo "<br/>";
        // exit;
//        $data = [];

        foreach ($shopIds as $key => $value) {

            $where = [];

            array_push($where,['shop_market_id','=',$value]);

            $start_time_ym = date('Ym',strtotime($start_time_int));

            $end_time_ym = date('Ym',strtotime($end_time_int));

            array_push($where,['yearmoneth','>=',$start_time_ym]);

            array_push($where,['yearmoneth','<=',$end_time_ym]);

            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";
            // exit;

            $shopGGF = Db::name('shop_market_moneth')->where($where)->select()->toArray();

            $moneyArr = array_values(array_unique(array_column($shopGGF,'advertising_expenses')));

            $data[$value]['ggf_huifang'] = '0.00';

            $data[$value]['ggf_tuangou'] = '0.00';

            if($shopGGF){

                foreach ($shopGGF as $k => $v) {

                    if($v['shop_market_type'] == '1'){

                        $data[$value]['ggf_huifang'] = bcadd($v['advertising_expenses'],0,2);

                    }

                    if($v['shop_market_type'] == '2'){

                        $data[$value]['ggf_tuangou'] = bcadd($v['advertising_expenses'],0,2);

                    }

                }

            }
            // else{

            //     $data[$value]['ggf_huifang'] = '0.00';

            //     $data[$value]['ggf_tuangou'] = '0.00';

            // }

            $data[$value]['ggf_all'] = bcadd(array_sum($moneyArr),0,2);

        }

        return $data;

    }

}

